如何生成名称为今天的日期的文件? [英] 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.
我正在Python中创建文件,如下所示:
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')
您可以更改格式但是你喜欢。上面的代码将打印出 datestring
,像这样:
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'
以下是全部内容:
>>> 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'
这篇关于如何生成名称为今天的日期的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!