212

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?

ARK
  • 772
  • 7
  • 21
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173

5 Answers5

303

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.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 4
    Which is great *unless* your time strings have 0.00pm, (`%I` starts at 1) !! – Andy Hayden Apr 20 '15 at 23:10
  • 5
    @AndyHayden it is 12 PM or 12 AM. Not sure if 0 AM or 0 PM make sense. Only in 24-hour format 0th hour makes sense, but then it is not AM/PM. – arun May 15 '20 at 17:46
  • 1
    Also note to have your locale in check. If you are using a locale which doesn't use a.m./p.m. you will have to switch to a locale that does use a.m./p.m. I used %I and %p and %p was left blank when using de_DE as locale. Switching to en_GB made %p visible. – Torsten Jul 17 '20 at 12:17
88
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.

jamessan
  • 41,569
  • 8
  • 85
  • 85
32

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

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
19

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

keithjgrant
  • 12,421
  • 6
  • 54
  • 88
19

Try replacing %I with %H.

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

Becomes

from datetime import datetime
print(datetime.today().strftime("%I:%M %p")) # 03:31 AM
Satyam Anand
  • 437
  • 4
  • 11
  • 6
    Welcome to StackOverflow. While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – Ruli Nov 04 '20 at 15:32