mystack
mystack

Reputation: 5502

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.

Upvotes: 4

Views: 16723

Answers (3)

defuz
defuz

Reputation: 27611

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)

Upvotes: 10

sabbahillel
sabbahillel

Reputation: 4425

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.

Upvotes: 3

mystack
mystack

Reputation: 5502

i got the solution Added following code

csvFile.close()

Upvotes: 0

Related Questions