Specifically I have code that simplifies to this:
from datetime import datetime date_string = '2009-11-29 03:17 PM' format = '%Y-%m-%d %H:%M %p' my_date = datetime.strptime(date_string, format) # This prints '2009-11-29 03:17 AM' print my_date.strftime(format)
What gives? Does Python just ignore the period specifier when parsing dates or am I doing something stupid?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The Python time.strftime docs say:
When used with the strptime() function, the
%pdirective only
affects the output hour field if the%Idirective is used to parse
the hour.
Sure enough, changing your %H to %I makes it work.
Method 2
format = '%Y-%m-%d %H:%M %p'
The format is using %H instead of %I. Since %H is the “24-hour” format, it’s likely just discarding the %p information. It works just fine if you change the %H to %I.
Method 3
You used %H (24 hour format) instead of %I (12 hour format).
Method 4
Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?
Method 5
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I with %H.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0