Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing date/time strings in Pandas DataFrame

Tags:

python

pandas

I have the following Pandas series of dates/times:

pd.DataFrame({"GMT":["13 Feb 20089:30 AM", "22 Apr 20098:30 AM", 
                    "14 Jul 20108:30 AM", "01 Jan 20118:30 AM"]})  


       GMT
13 Feb 20089:30 AM
22 Apr 20098:30 AM
14 Jul 20108:30 AM
01 Jan 20118:30 AM

What I would like is to split the date and time portions into two separate columns, i.e.

    Date         Time
13 Feb 2008     9:30 AM
22 Apr 2009     8:30 AM
14 Jul 2010     8:30 AM
01 Jan 2011     8:30 AM

Any help? Thought about simply splicing each string individually but was wondering if there was a better solution that returned them as datetime objects.

like image 333
measure_theory Avatar asked Mar 09 '23 02:03

measure_theory


1 Answers

Use to_datetime + dt.strftime:

df['GMT'] = pd.to_datetime(df['GMT'], format='%d %b %Y%H:%M %p')

df['Date'] = df['GMT'].dt.strftime('%d %b %Y')
df['Time'] = df['GMT'].dt.strftime('%H:%M %p')
print (df)
                  GMT         Date      Time
0 2008-02-13 09:30:00  13 Feb 2008  09:30 AM
1 2009-04-22 08:30:00  22 Apr 2009  08:30 AM
2 2010-07-14 08:30:00  14 Jul 2010  08:30 AM
3 2011-01-01 08:30:00  01 Jan 2011  08:30 AM

And for datetime objects use dt.date and dt.time:

df['GMT'] = pd.to_datetime(df['GMT'], format='%d %b %Y%H:%M %p')
df['Date'] = df['GMT'].dt.date
df['Time'] = df['GMT'].dt.time
print (df)
                  GMT        Date      Time
0 2008-02-13 09:30:00  2008-02-13  09:30:00
1 2009-04-22 08:30:00  2009-04-22  08:30:00
2 2010-07-14 08:30:00  2010-07-14  08:30:00
3 2011-01-01 08:30:00  2011-01-01  08:30:00

For formats check http://strftime.org/.

like image 53
jezrael Avatar answered Mar 20 '23 23:03

jezrael