Create a File Name with Current Date & Time in Python

Posted on August 26, 2019 at 12:19 pm

In Python you can get the current date and time like this:

import time
timestr = time.strftime("%Y-%m-%d_%H-%M-%S")
print(timestr)

Here is an example output:

2019-08-11_15-23-02

Then you can use timestr variable as file name, i.e:

file = open(timestr+'.txt', 'w')
file.write('whatever')
file.close()

Or another example below:

with open(timestr+'.txt', 'w') as file:
    file.write('whatever')

Receive updates via email

Other Posts

Updated Posts