Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert dates into ISO-8601 DateTime format in a Pandas dataframe

I have the dataframe below (using python/pandas) and wish to convert the

q_string          q_visits  q_date
red               1790  02/10/2012 00:00
blue              364   02/10/2012 00:00
current           280   02/10/2012 00:00
molecular         259   02/10/2012 00:00
cell              201   02/10/2012 00:00

How can I convert the 'q_date' field into SO-8601 DateTime format (yyyy-MM- ddTHH:mm:ssZ)?

Thanks in advance.

like image 353
user7289 Avatar asked Sep 04 '13 15:09

user7289


2 Answers

Use the pandas datetools parser to parse the date and then format it using the standard python strftime function.

>>> df['q_date'].apply(
        lambda x: pd.datetools.parse(x).strftime('%Y-%m-%dT%H:%M:%SZ'))
0    20120210T00:0000Z
1    20120210T00:0000Z
2    20120210T00:0000Z
3    20120210T00:0000Z
4    20120210T00:0000Z
Name: q_date, dtype: object
like image 160
Viktor Kerkez Avatar answered Sep 28 '22 10:09

Viktor Kerkez


I would use pd.to_datetime and the .dt accessor

pd.to_datetime(df['q_date']).dt.strftime('%Y-%m-%dT%H:%M:%SZ')

See also strftime() and strptime() Format Codes

like image 41
Casey Clements Avatar answered Sep 28 '22 09:09

Casey Clements