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.
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With