0

I'm trying to open a file with the name as the date and time formatted as dd-mm-yy hh:mm:ss. Doing this:

from datetime import datetime
timestr = datetime.now().strftime("%d-%m-%y %H:%M:%S")
print(timestr)
f = open(timestr, "w+")
f.close()

always results in this error:

C:\Users\keona\Documents\Py>timetest.py
14-09-19 21:28:19
Traceback (most recent call last):
  File "C:\Users\keona\Documents\Py\timetest.py", line 4, in <module>
    f = open(timestr, "w+")
OSError: [Errno 22] Invalid argument: '14-09-19 21:28:19'

However, the code works when I take off the seconds, for some reason??

from datetime import datetime
timestr = datetime.now().strftime("%d-%m-%y %H:%M")
print(timestr)
f = open(timestr, "w+")
f.close()

which results in a file named only this:

14-09-19 21

Any suggestions or ideas as to why this is happening?

1 Answers1

2

I'd say it might be because : is an invalid character in a filename in windows.

Try using strftime("%d-%m-%y %H-%M-%S")

Emil Vatai
  • 2,298
  • 1
  • 18
  • 16