1

so below example of code:

 >>> from datetime import datetime
 >>> future = datetime.strptime('12:00', '%I:%M')
 >>> past = datetime.strptime('11:59', '%I:%M')
 >>> future < past 
 >>> True # expected False, because '12:00' > '11:59'
 >>> past_2 = datetime.strptime('11:58', '%I:%M')
 >>> past < past_2
 >>> False

why datetime compare operation returns True instead of False?

holdenweb
  • 33,305
  • 7
  • 57
  • 77
SergeySD
  • 83
  • 1
  • 2
  • 7

3 Answers3

4

%I is the hours for a twelve hour clock. Unless you supply an AM or PM (%p), it takes the AM choice. 12:00 AM (i.e. midnight) is before 11:59 AM.

If you use %H you get 24 hour clock, in which 12:00 will be noon instead of midnight.

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

strptime in this case maps '12:00' to midnight ... the format specifier %I "means": "Hour (12-hour clock) as a zero-padded decimal number."

Dilettant
  • 3,267
  • 3
  • 29
  • 29
0

The issue here is which 12:00 you mean. Printing out the datetimes in question might help you to understand:

future, past, past_2

has the value:

(datetime.datetime(1900, 1, 1, 0, 0),
 datetime.datetime(1900, 1, 1, 11, 59),
 datetime.datetime(1900, 1, 1, 11, 58))

As you can see, 12:00 is interpreted as being at the start of the day, while 11:59 is interpreted as almost midday, 11 hours and 59 minutes later.

holdenweb
  • 33,305
  • 7
  • 57
  • 77