Imam Abdul Mahmudi
Imam Abdul Mahmudi

Reputation: 303

How to write the timestamp when exporting to CSV in Python?

I want to add timestamp (DD-MM-YYYY h:m:s) every time I write data to a CSV file. This is my code:

def WriteListtoCSV(data):
    with open ('tesdata.csv','a') as csvfile:
        writer = csv.writer(csvfile)
            for val in data:
                writer.writerow([val])

In every write row I want to write TimeStamp in column 1 and data in column 2.

Upvotes: 3

Views: 11244

Answers (1)

Alexander
Alexander

Reputation: 109616

The time module will give you the current system time, and it supports a strftime() method where you format the time per your requirement ('DD-MM-YYY h:m:s').

import time

for val in data:
    now = time.strftime('%d-%m-%Y %H:%M:%S')
    writer.writerow([now, val])

Upvotes: 3

Related Questions