Reputation: 9
I am getting the following error:
ValueError: time data 'Feb 1, 2017 0:03 pm' does not match format '%b %d, %Y %I:%M %p'
Here is the code :
from datetime import datetime
latest_datetime = 'Feb 1, 2017 0:03 pm'
datetime_obj = datetime.strptime(latest_datetime, "%b %d, %Y %I:%M %p")
I'm unable to figure out why I get the error.
Upvotes: 0
Views: 1304
Reputation: 1121346
A 12-hour clock has no 0
hour; %I
will only match 1 through to 12. Your timestamp has an impossible time in it:
0:03 pm
From the strftime()
and strptime()
Behavior documentation:
%I
Hour (12-hour clock) as a zero-padded decimal number.
01, 02, ..., 12
Assuming 0
is really 12
, you could repair this by replacing the ' 0:'
with '12:'
(note the leading space for the zero!):
>>> from datetime import datetime
>>> latest_datetime = 'Feb 1, 2017 0:03 pm'
>>> datetime.strptime(latest_datetime.replace(' 0:', '12:'), "%b %d, %Y %I:%M %p")
datetime.datetime(2017, 2, 1, 12, 3)
It doesn't really matter if you have one or two spaces between the year and the hour, the string will be parsed either way.
Upvotes: 2