Home > Software engineering >  Using pandas to save to a csv file with date time appended to the filename
Using pandas to save to a csv file with date time appended to the filename

Time:09-30

I was running the code but am getting this error

OSError: [Errno 22] Invalid argument: 'filename 09-30-2021 16:45:17 PM.csv'

Is there anyway to work around this?

currentDateTime = datetime.now().strftime("%m-%d-%Y %H:%M:%S %p")
df.to_csv(f"filename {currentDateTime}.csv", index = False)

CodePudding user response:

Try this instead. Because, you cannot have colons (:) in filenames.

currentDateTime = datetime.now().strftime("%m-%d-%Y %H-%M-%S %p")
df.to_csv(f"filename {currentDateTime}.csv", index = False)

CodePudding user response:

Your example works on Linux, but it doesn't work on Windows because of the restricted characters: < > : " / \ | ? *

Please replace : with something else.

  • Related