简体   繁体   中英

How can I generate a file with today's date in its name?

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...

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'

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'

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