How can I account for period (AM/PM) using strftime?

PythonDatetimeStrptime

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

The Python time.strftime docs say:

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

Sure enough, changing your %H to %I makes it work.

Solution 2 - Python

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.

Solution 3 - Python

You used %H (24 hour format) instead of %I (12 hour format).

Solution 4 - Python

Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?

Solution 5 - Python

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKenan BanksView Question on Stackoverflow
Solution 1 - PythonNed BatchelderView Answer on Stackoverflow
Solution 2 - PythonjamessanView Answer on Stackoverflow
Solution 3 - PythonTim PietzckerView Answer on Stackoverflow
Solution 4 - PythonkeithjgrantView Answer on Stackoverflow
Solution 5 - PythonSatyam AnandView Answer on Stackoverflow