7

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.

2
  • I think its better if you have a space between 2008 and 9 like 2008 9 instead of 20089 , because the logic becomes very elaborate to do something with 20089 Commented May 15, 2017 at 11:16
  • That's how the data comes, it isn't something I can choose. Commented May 15, 2017 at 11:17

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.