简体   繁体   中英

How to write current datetime to a csv file in python?

I used following code for writing the datetime to a csv file.

csvdata=[datetime.datetime.now()]
csvFile=open("Datetime.csv","w")
Fileout=csv.writer(csvFile, delimiter=',',quoting=csv.QUOTE_ALL)
Fileout.writerow(csvdata)

Eventhough the file is creating it have no data in it.What should i do in extra for getting the data in csv.

The problem is that the writing of the file is buffered, and does not happen immediately. You should close your file descriptor to flushes any unwritten data:

csvFile.close()

Or just use with statement (recommended):

csvdata = [datetime.datetime.now()]
with open("Datetime.csv","w") as csvFile:
    Fileout = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL)
    Fileout.writerow(csvdata)

You should use strftime() to create the date and time in the format that you need such as

mydate = datetime.datetime.now()
csvstr = datetime.datetime.strftime(mydate, '%Y, %m, %d, %H, %M, %S')

This is besides closing or flushing the file to force the buffer output. The way that you asked the question implied that you were not seeing output data after the python program had exited, which would have closed the file as part of the exit processing.

I would also remember to make the header row, the first row in the output file.

我得到了解决方案添加了以下代码

csvFile.close()

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