简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM