Predictive Hacks

How to Generate a File Name that includes the Creation Date

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'

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.