pythondatetimestrptimestrftime

How to convert string containing AM/PM to datetime in python using %p


I need to convert a string formatted as '2000-01-01 12:00:00 AM' but it doesn't matter if it is AM or PM the result is the same (see example below).

from datetime import datetime
frmt = '%Y-%d-%m %H:%M:%S %p'
datetime.strptime('2000-01-01 12:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 12:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T12:00:00'
'2000-01-01T12:00:00'

I thought it could be a problem related to no definition if 12AM is midnight or noon but even when executing the same code for other different hours the result is still the same:

datetime.strptime('2000-01-01 06:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 06:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T06:00:00'
'2000-01-01T06:00:00'

The strftime.org website says the format I am using should work, but it is not. What should I do?


Solution

  • This is why I use arrow. Just makes all of this easier.

    import arrow
    frmt = 'YYYY-MM-DD HH:mm:ss A'
    print(arrow.get('2000-01-01 12:00:00 AM', frmt))
    print(arrow.get('2000-01-01 12:00:00 PM', frmt))
    #datetime
    print(arrow.get('2000-01-01 12:00:00 AM', frmt).datetime)
    print(arrow.get('2000-01-01 12:00:00 PM', frmt).datetime)
    #isoformat
    print(arrow.get('2000-01-01 12:00:00 AM', frmt).isoformat())
    print(arrow.get('2000-01-01 12:00:00 PM', frmt).isoformat())