datetime to string with series in pandas
I need to make this simple thing:
dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str
But I get an error. How should I transform from datetime
to string
?
Solution 1:
There is no str
accessor for datetimes and you can't do dates.astype(str)
either, you can call apply
and use datetime.strftime
:
In [73]:
dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0 2001-01-01
1 2001-03-31
dtype: object
You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.
Update
As of version 0.17.0
you can do this using dt.strftime
dates.dt.strftime('%Y-%m-%d')
will now work
Solution 2:
As of version 17.0, you can format with the dt
accessor:
dates.dt.strftime('%Y-%m-%d')
Reference
Solution 3:
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.