Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas datetime64 to string

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']
like image 407
Kavita Avatar asked May 21 '18 12:05

Kavita


People also ask

How do I convert datetime64 to NS to string in Python?

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.

What is datetime64 in Python?

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.


Video Answer


1 Answers

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']
like image 83
EdChum Avatar answered Oct 20 '22 12:10

EdChum