Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime format change when save to csv file python

Tags:

python

pandas

I have a dataframe like this:

In [67]:
call_df.head()
Out[67]:
timestamp   types
1   2014-06-30 07:00:55 Call_O
2   2014-06-30 07:00:05 Call_O
3   2014-06-30 06:54:55 Call_O
501 2014-06-30 11:24:01 Call_O

When I saved that dataframe to csv file, the format of datetime is change as well as I lose the seconds. I just put this code to save into csv file:

call_df.to_csv('D:/Call.csv')

The csv file output is like this:

enter image description here

In here I want to ask, how to save the same datetime format from dataframe into csv file

like image 323
markov zain Avatar asked May 18 '15 08:05

markov zain


1 Answers

The answer to this problem is a two-step process:

1) Convert the timestamp column to date time first:

call_df['timestamp'] = call_df['timestamp'].astype('datetime64[ns]')

2) Add date_format argument while using the "to_csv" after performing the first step:

call_df.to_csv("Call.csv", date_format='%Y-%m-%d %H:%M:%S')
like image 76
Gurtej Khanooja Avatar answered Oct 21 '22 21:10

Gurtej Khanooja