Let’s say that every single day, we have to generate a report, and we want to add as a suffix the creation date to the file name. Let’s see how we can do it. For convenience, the date will be of the form yyyymmdd
since this allows us to sort the files based on file name achieving a sorting of creating date :
from datetime import datetime mydate = datetime.now() myfilename = "report_"+mydate.strftime('%Y%m%d')+".csv" myfilename
And we get:
'report_20210518.csv'
Note that we added the required extension of the file name. It could .txt
etc or nothing in the case of a flat file.
Finally, we can add the time if we want as follows:
myfilename = "report_"+mydate.strftime('%Y%m%d-%H%M%S')+".csv" myfilename
Output:
'report_20210518-133907.csv'