Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv writerows reformatting datetime to include seconds

Using Python, I have a datetime object in a list. The datetime format I want and have during program execution is (%Y/%m/%d %H:%M).

Then, I use csv.writer and writerows (on a list of list) to save a file.

However, when I open text file, all the dates and times now include seconds, :00 .

Why is saving the file causing seconds to be added to the time?

EDIT for display of value & code: This is the print of the object: datetime.datetime(2014, 3, 17, 8, 10)

with open(FinalSaveFileName, 'wb') as ffn:
w = csv.writer(ffn, dialect = 'excel-tab')
w.writerows(List)

After opening in Notepad++ (not Excel), "2014-03-17 08:10:00" for this column.

like image 531
Mark Avatar asked Oct 31 '22 19:10

Mark


1 Answers

It looks like your datetimes are being coerced to strings with the default format. If you want to use another format for dates, then convert them to strings yourself before sending them to csv.writer. There is a good example of this take from here:

import datetime

with open('file.csv','w') as outputfile:
    for row in rows:
        wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
        #change row[1] to wherever your datetime is
        row[1] = row[1].strftime('%Y/%m/%d %H:%M')
        wrtr.writerow(row)
like image 181
Andrew Johnson Avatar answered Nov 15 '22 05:11

Andrew Johnson