SergeySD SergeySD - 1 year ago 116
Python Question

Python datetime comparison is incorrect in case of compare two time like: 12:00 and 11:59

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?

Answer Source

%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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download