How to create a file name with the current date & time in Python?
While not using datetime
, this solves your problem (answers your question) of getting a string with the current time and date format you specify:
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
print timestr
yields:
20120515-155045
so your filename could append or use this string.
Change this line
filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
To
filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
Note the extra datetime
. Alternatively, change your
import datetime
to from datetime import datetime
now
is a class method in the class datetime
in the module datetime
. So you need
datetime.datetime.now()
Or you can use a different import
from datetime import datetime
Done this way allows you to use datetime.now
as per the code in the question.
This one is much more human readable.
from datetime import datetime
datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")
'2020_08_12-03_29_22_AM'
I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time,
We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'
"%x" instead of "%Y%m%d-%H%M%S"