Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert column of date objects in Pandas DataFrame to strings

How to convert a column consisting of datetime64 objects to a strings that would read 01-11-2013 for today's date of November 1.

I have tried

df['DateStr'] = df['DateObj'].strftime('%d%m%Y') 

but I get this error

AttributeError: 'Series' object has no attribute 'strftime'

like image 571
user2333196 Avatar asked Nov 02 '13 01:11

user2333196


People also ask

How do you convert a date column to a string in Python?

Use astype() to Change datetime to String Format You can use this if the date is already in the format you want it in string form. The below example returns the date as a string with format %Y/%m/%d . dtype of column ConvertedDate will be object ( string ).

How do you turn a column into a string?

You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .


2 Answers

As of version 17.0, you can format with the dt accessor:

df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y') 
like image 130
Kamil Sindi Avatar answered Oct 07 '22 07:10

Kamil Sindi


In [6]: df = DataFrame(dict(A = date_range('20130101',periods=10)))  In [7]: df Out[7]:                      A 0 2013-01-01 00:00:00 1 2013-01-02 00:00:00 2 2013-01-03 00:00:00 3 2013-01-04 00:00:00 4 2013-01-05 00:00:00 5 2013-01-06 00:00:00 6 2013-01-07 00:00:00 7 2013-01-08 00:00:00 8 2013-01-09 00:00:00 9 2013-01-10 00:00:00  In [8]: df['A'].apply(lambda x: x.strftime('%d%m%Y')) Out[8]:  0    01012013 1    02012013 2    03012013 3    04012013 4    05012013 5    06012013 6    07012013 7    08012013 8    09012013 9    10012013 Name: A, dtype: object 
like image 31
Jeff Avatar answered Oct 07 '22 07:10

Jeff