I am converting pandas dataframe column of datetime64 to list and then exporting into single column of csv.
In CSV I get values as
"[Timestamp('2018-05-20 10:20:00'), Timestamp('2018-05-20 10:30:00')]"
How can I convert to string and export to CSV. I would like to have data as below:
['2018-05-20 10:20:00', '2018-05-20 10:30:00']
Pandas Convert Date to String Format – To change/convert the pandas datetime ( datetime64[ns] ) from default format to String/Object or custom format use pandas. Series. dt. strftime() method.
The datetime64 function in python allows the array representation of dates to the user. It takes the input in a particular format. Below given is the basic syntax of using the datetime64 function in a Python program: numpy.datetime64('dates') Output generated by the datetime64 function is in 'yyyy-mm-dd' format.
You can just cast the dtype first using astype
:
In[29]:
df = pd.DataFrame({'date':pd.to_datetime(['2018-05-20 10:20:00','2018-05-20 10:30:00'])})
df
Out[29]:
date
0 2018-05-20 10:20:00
1 2018-05-20 10:30:00
In[30]:
df['date'].astype(str).tolist()
Out[30]: ['2018-05-20 10:20:00', '2018-05-20 10:30:00']
What you did just converted the array to a list of the original dtype:
In[31]:
df['date'].tolist()
Out[31]: [Timestamp('2018-05-20 10:20:00'), Timestamp('2018-05-20 10:30:00')]
The more formal method is to call dt.strftime
to convert to string using the passed in format:
In[33]:
df['date'].dt.strftime('%Y-%m-%d %H:%M:%S').tolist()
Out[33]: ['2018-05-20 10:20:00', '2018-05-20 10:30:00']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With