from datetime import datetime, date, time
now = datetime.now()
print now #2013-05-23 04:07:40.951726
tar = tarfile.open("test.tar", "w")
How to add the date to the file name? For example: test2013_05_23_04_07.tar
With string formatting.
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")
Or using .format()
in Python 3.+
tar = tarfile.open("test{}.tar".format(now), "w")
Note, you can also decide how you want datetime.now()
to be displayed using .strftime()
:
print now.strftime('%Y-%m-%d')
>>> 2013-05-23
I have a function I use fairly often:
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S-{fname}'):
import datetime
# This creates a timestamped filename so we don't overwrite our good work
return datetime.datetime.now().strftime(fmt).format(fname=fname)
invoke with
fname = timeStamped('myfile.xls')
Result: 2013-05-23-08-20-43-myfile.xls
Or change the fmt:
fname2 = timeStamped('myfile.xls', '%Y%m%d-{fname}')
Result: 20130523-myfile.xls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With