如何将日期添加到文件名?

dev*_*ght 1 python

from datetime import datetime, date, time

now = datetime.now()
print now #2013-05-23 04:07:40.951726    
tar = tarfile.open("test.tar", "w")
Run Code Online (Sandbox Code Playgroud)

如何将日期添加到文件名?例如:test2013_05_23_04_07.tar

Inb*_*ose 6

使用字符串格式.

from datetime import datetime, date, time

now = datetime.now()
print now #2013-05-23 04:07:40.951726    
tar = tarfile.open("test%s.tar" % now, "w")
Run Code Online (Sandbox Code Playgroud)

或者.format()在Python 3 +中使用

tar = tarfile.open("test{}.tar".format(now), "w")
Run Code Online (Sandbox Code Playgroud)

注意,您还可以决定如何datetime.now()使用.strftime()以下方式显示:

print now.strftime('%Y-%m-%d')
>>> 2013-05-23
Run Code Online (Sandbox Code Playgroud)