Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify date format when using pandas.to_csv?

People also ask

What does to_csv do in pandas?

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.

Which function to change the date format in pandas DataFrame?

Function usedstrftime() can change the date format in python. Where, format is a string representing the type of required date format.


Since version v0.13.0 (January 3, 2014) of Pandas you can use the date_format parameter of the to_csv method:

df.to_csv(filename, date_format='%Y%m%d')

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')

To export as a timestamp, do this:

df.to_csv(filename, date_format='%s')

The %s format is not documented in python/pandas but works in this case.

I found the %s from the dates formats of ruby. Strftime doc for C here

Note that the timestamp miliseconds format %Q does not work with pandas (you'll have a litteral %Q in the field instead of the date). I caried my sets with python 3.6 and pandas 0.24.1