Frederic Bastiat
Frederic Bastiat

Reputation: 693

hourly to_period 24 hour format ignored

Sample string:

11/8/2017 3:00:00 PM

Which is in the dataframe column sales['Checkin']

Code for conversion:

pd.to_datetime(sales['Checkin'], format = "%m/%d/%Y %H:%M:%S %p").dt.to_period('H')

This results in:

2017-11-08 03:00

Thus ignoring the PM... I expected correct result:

2017-11-08 15:00

I tested it and it seems to be an issue with to_datetime and not to_period, but I'm not sure what I'm missing because I googled and noticed I am using %H correctly, and not %I which is the 12 hour format...

Upvotes: 1

Views: 464

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375925

You have to use %I rather than %H:

In [11]: pd.to_datetime(s, format = "%m/%d/%Y %I:%M:%S %p").dt.to_period('H')
Out[11]:
0   2017-11-08 15:00
dtype: object

From the datetime formatting docs:

%H  Hour (24-hour clock) as a zero-padded decimal number.    
%I  Hour (12-hour clock) as a zero-padded decimal number.

Upvotes: 2

Related Questions