Search code examples
pythonpython-3.xpython-datetime

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

  • 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