Search code examples
pythondatetimecomparisonpython-datetimetimedelta

How to compare timedelta object with time object in python


I had one time object I used timedelta to add 5 hours and 30 minutes to it now I have one timedelta object

new_time2 = timedelta(hours=starttime_time.hour+5, minutes=starttime_time.minute+30)
print(new_time2, type(new_time2))
>>>15:30:00 <class 'datetime.timedelta'>

Now I have another time object

input_time = "09:30:00"
a = datetime.strptime(input_time, '%H:%M:%S').time()
print(a, type(a))
>>>09:30:00 <class 'datetime.time'>

So I want to compare these two times but when I am doing this I am getting a TypeError

print(new_time2 >= a)

TypeError: '>=' not supported between instances of 'datetime.timedelta' and 'datetime.time'
09:30:00 <class 'datetime.time'>

So is there any other way I can compare these two times. Thanks in advance.


Solution

  • You can convert the time instance to timedelta:

    >>> from datetime import timedelta
    >>> e = timedelta(hours=a.hour, minutes=a.minute, seconds=a.second)
    >>> print(e, type(e))
    9:30:00 <class 'datetime.timedelta'>
    

    then you can compare:

    >>> print(new_time2 >= e)
    True