Reputation: 67
I have seen several post like this but nobody actually answer the question straight to the point.
I'm creating a file in Python like this:
f = open('myfile.extension','w')
What should I add to this line to add the date in the filename?
I'm using import time
and I can get any current date in any other part of my script, but I don't know how to add the date...
Upvotes: 1
Views: 13484
Reputation: 2782
Assuming you are trying to add the date to the filename
from datetime import datetime
datestring = datetime.strftime(datetime.now(), '%Y/%m/%d_%H:%M:%S')
f = open('myfile_'+datestring+'.extension', 'w')
You can change the format however you like. The above will print out datestring
like so:
datetime.strftime(datetime.now(), '%Y/%m/%d_%H:%M:%S')
'2015/08/07_16:07:37'
Of course since this is a filename you may not want to have the /
, so I would recommend a format like the following:
datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
'2015-08-07-16-07-37'
Here's a full run of all of the above:
>>> from datetime import datetime
>>> datestring = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
>>> f = open('myfile_' + datestring + '.ext', 'w')
>>> f.name
'myfile_2015-08-07-16-24-23.ext'
Upvotes: 7
Reputation: 21
I'm assuming you want it in the filename:
from datetime import date
filename = 'myfile_{}.extension'.format(date.today())
f = open(filename, 'w')
print f.name # 'myfile_2015-08-07.extension'
Upvotes: 2