Search code examples
pythonpandasdataframepython-requestsexport-to-csv

Add Timestamp to file name during saving Data Frame in csv


When I save a file to .csv I want to add next to it the timestamp when that file was created. I tried this one but it didnt work:

df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) 

It is giving me this output:

OSError: [Errno 22] Invalid argument: 'File_name_2021-05-12 16:20:23.csv'

How do I correct this?


Solution

  • Colons are not permitted in filenames on Windows, so you can use your line sans-colons and it should work fine:

    df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H%M%S")))
    

    Per Microsoft Documentation:

    Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

    • The following reserved characters:

      • < (less than)
      • > (greater than)
      • : (colon)
      • " (double quote)
      • / (forward slash)
      • \ (backslash)
      • | (vertical bar or pipe)
      • ? (question mark)
      • * (asterisk)
    • Integer value zero, sometimes referred to as the ASCII NUL character.

    • Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.

    • Any other character that the target file system does not allow.