Search code examples
pandascsvexport-to-csv

How do you save a pandas csv file with the exact date leading down to the seconds


I'm trying to save my csv files as today's date in the format: 'Wed Dec 9 04:26:40 2020'.

I've tried using time.ctime():

excelfilename = 'file' + TodaysDate + ".csv"
data.to_csv(excelfilename , index=False)

but I get the error:

OSError: [Errno 22] Invalid argument: 'file Dec  5 17:38:58 2020.csv'

Is there another way around this?


Solution

  • I don't think you can use : in a filename on Mac or Windows OS.

    Try this:

    import pandas as pd
    from datetime import datetime
    df = pd.read_csv('<your original file here>')
    now_ = datetime.now().strftime('%b %d %y %H_%M_%S')
    df.to_csv('file ' + now_ + '.csv', index=False)
    

    The file will be exported with this name:

    print('file ' + datetime.now().strftime('%b %d %y %H_%M_%S') + '.csv')`
    >>> file Dec 05 20 12_09_26.csv