简体   繁体   English

如何生成名称为今天的日期的文件?

[英]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: 我正在像这样在Python中创建文件:

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... 我正在使用import time并且可以在脚本的任何其他部分获取任何当前日期,但是我不知道如何添加日期...

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: 上面将打印出日期datestring如下所示:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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