How can I account for period (AM/PM) with datetime.strptime?

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


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.


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.


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


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


Need Your Help

The function to show current file's full path in mini buffer

emacs elisp clipboard aquamacs

I need to get the full path of the file that I'm editing with emacs.

Python division

python math python-2.x

I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expe...