How to create a file name with the current date & time in Python?

Here is a functional code (create file with success)

sys.stdout = open('filename1.xml', 'w')

Now I’m trying to name the file with the current date/time (I’m not an expert in Python)

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')

I want to write out a file name with the exact date and time, it is a xml file, that the program has already create, I just need to name the file. The above code is not working.

The error returned:

  File "./fix.py", line 226, in <module>
    filenames = datetime.now().strftime("%Y%m%d-%H%M%S")
AttributeError: 'module' object has no attribute 'now'

8 Answers
8

Leave a Comment