Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime to string with series in pandas

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

dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d') dates.str 
like image 521
Diego Avatar asked May 08 '15 20:05

Diego


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 ).

What does DT Strftime do?

strftime() function is used to convert to Index using specified date_format. The function return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library.


2 Answers

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 
like image 76
EdChum Avatar answered Sep 29 '22 08:09

EdChum


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

dates.dt.strftime('%Y-%m-%d') 
like image 23
Kamil Sindi Avatar answered Sep 29 '22 08:09

Kamil Sindi