Reputation: 859
I have two columns First
and Last
(both dtypes are object) that I would like to turn them into time variables, lets call it First_time
, Last_time
.
Current Dataframe
ID First Last
1 7:30a 4p
2 10a 6p
3 7p 3:30a
Desired Dataframe
ID First Last
1 07:30 16:00
2 10:00 18:00
3 19:00 03:30
I found a useful site here https://www.journaldev.com/23365/python-string-to-datetime-strptime and have tried to apply the following code DF['hour'] = pd.to_datetime(DF['Last'], format='%H').dt.hour
However, I get the following error and I can tell it has something to do with the text next to the number. It's a long error so I will just post the lines in red:
TypeError: Unrecognized value type: <class 'str'>
ValueError Traceback (most recent call last)
ValueError: unconverted data remains: p
Upvotes: 1
Views: 61
Reputation: 77847
Re-read that link you posted. The table clearly delineates the accepted formats. 4p
is not in any of these formats. However, 4pm
is in one of those, the %p specification. Start with
DF['hour'] = pd.to_datetime(DF['Last']+['m'], format='%H%p').dt.hour
and work from there.
Upvotes: 3