0

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.

0

1 Answer 1

2

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.

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

1 Comment

You are right, I did a bad/rushed diagnostic playing on the console.

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.