92

How should I transform from datetime to string? My attempt:

dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Diego
  • 2,196
  • 1
  • 21
  • 26

3 Answers3

165

There is no .str accessor for datetimes and you can't do .astype(str) either.

Instead, use .dt.strftime:

>>> series = pd.Series(['20010101', '20010331'])
>>> dates = pd.to_datetime(series, format='%Y%m%d')
>>> dates.dt.strftime('%Y-%m-%d')
0    2001-01-01
1    2001-03-31
dtype: object

See the docs on customizing date string formats here: strftime() and strptime() Behavior.


For old pandas versions <0.17.0, one can instead can call .apply with the Python standard library's datetime.strftime:

>>> dates.apply(lambda x: x.strftime('%Y-%m-%d'))
0    2001-01-01
1    2001-03-31
dtype: object
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • Thanks @EdChum. But now I found another problem. If a have NaT.? How to solve it ? `dates = p.to_datetime(p.Series(['20010101', '20010331',None]), format = '%Y%m%d') dates.apply(lambda x: x.strftime('%Y-%m-%d'))` – Diego May 08 '15 at 21:39
  • 1
    Drop them first is one option so `dates.dropna().apply(lambda x: x.strftime('%Y-%m-%d'))` – EdChum May 08 '15 at 21:40
  • @EdChum This still doesn't turn dates into strings. `type(dates.df.strftime(...))` says ``. You need to add `.tolist()`. pandas version 0.25.3 – horaceT Oct 20 '20 at 18:52
50

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

dates.dt.strftime('%Y-%m-%d')
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Kamil Sindi
  • 21,782
  • 19
  • 96
  • 120
  • 1
    this sped up my code 10 fold compared to using `datetime.strftime` inside a lambda function in a dataframe `.apply()` method (as suggested by @EdChum) – Tanguy Oct 23 '19 at 08:20
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.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Qing Xia
  • 31
  • 2