Home > Software engineering >  Python datetime compare two time stamps without taking date into account
Python datetime compare two time stamps without taking date into account

Time:04-08

Say I have two times in Python as string

import datetime
time1 = '16:00'
time2 = '17:00'

Is there any way to do a logic as below, where I compare the two time points as if they are from the same day. Can I compare them without taking date into account?

if time1 < time2:
    print('True')

CodePudding user response:

With exactly the code you have written, you're actually just going to be comparing two strings to one another since neither of them has been parsed as a datetime object.

Is there a specific reason that you explicitly do not want the date? If this is purely for comparison purposes, then the following should work since it will parse both times as being from the same date:

from datetime import datetime

time1 = datetime.strptime("16:00", "%H:%M")
time2 = datetime.strptime("17:00", "%H:%M")
print(time1)
print(time2)

Running this code prints:

1900-01-01 16:00:00
1900-01-01 17:00:00

and the underlying datetime objects can now be compared as you wanted.

  • Related