Search code examples
pythonpandasexport-to-csvdatetime-formatdate-formatting

How to specify date format when using pandas.to_csv?


The default output format of to_csv() is:

12/14/2012  12:00:00 AM

I cannot figure out how to output only the date part with specific format:

20121214

or date and time in two separate columns in the csv file:

20121214,  084530

The documentation is too brief to give me any clue as to how to do these. Can anyone help?


Solution

  • You could use strftime to save these as separate columns:

    df['date'] = df['datetime'].apply(lambda x: x.strftime('%d%m%Y'))
    df['time'] = df['datetime'].apply(lambda x: x.strftime('%H%M%S'))
    

    and then be specific about which columns to export to csv:

    df[['date', 'time', ... ]].to_csv('df.csv')