create a file name with date in python

create a file name with date in python

We often may want to create the output file with a date in python. It makes more sense to append or prepend date to the file.

To do so, you have to import “time” module from python and use time.strftime() method. Specify t he format string to the method as desired.

You can achive it by using  the following piece of code.

import time

date_fname = time.strftime("%Y%m%d%H%M")
new_fname="my_file_"+ date_fname + ".txt"
print new_fname

f= open(new_fname,"w+")

test="Sample data"
f.write("%s" %test)


The statement “date_fname = time.strftime(“%Y%m%d%H%M”)”  will create a string in Year,month,day,hour,minute format. If you don’t want hour and minutes just use remove %H and %M from it.

But I would recommend to use  hour and minute because, if you write two files on the same day, you will end up overwriting the previos one.

You can even add “second” if you write files more frequently. To add second use following statement.

"date_fname = time.strftime("%Y%m%d%H%M%S")"


Leave a Reply

Your email address will not be published. Required fields are marked *