Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

strptime does not understand difference betwen 12:30 AM and 12:30 PM

Below are 2 datetime strings with AM/PM. The AM containing string returns the exact same datetime object value as the PM containing string. What am I doing wrong?

from datetime import datetime
format   ='%d %b %y %H:%M %p'

date_str ='23 Feb 22 12:57 PM'
print(datetime.strptime(date_str, format))
# 2022-02-23 12:57:00

date_str ='23 Feb 22 12:57 AM'
print(datetime.strptime(date_str, format))
# 2022-02-23 12:57:00

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Per https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

When used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.


>>> format   ='%d %b %y %I:%M %p'
>>> date_str ='23 Feb 22 12:57 AM'
>>> print(datetime.strptime(date_str, format))
2022-02-23 00:57:00

>>> date_str ='23 Feb 22 12:57 PM'
>>> print(datetime.strptime(date_str, format))
2022-02-23 12:57:00
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading