如何将 timedelta 对象与 python 中的时间对象进行比较

How to compare timedelta object with time object in python

我有一个时间对象我用 timedelta 添加了 5 小时 30 分钟现在我有一个 timedelta 对象

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'>

现在我又多了一个时间对象

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

所以我想比较这两次,但是当我这样做时我得到了一个 TypeError

print(new_time2 >= a)

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

那么有没有其他方法可以比较这两个时间。 提前致谢。

你创建了一个 timedelta 对象而不是 datetime 对象..让我举个例子:

>>> from datetime import datetime, timedelta
>>>
>>> t1 = datetime.now()
>>> t1
datetime.datetime(2022, 1, 11, 13, 34, 37, 537863)
>>>
>>> tenMinsDelta = timedelta(minutes=10)
>>>
>>> t1PlusTen = t1 + tenMinsDelta
>>>
>>>
>>> type(t1PlusTen)
<class 'datetime.datetime'>
>>>
>>> type(tenMinsDelta)
<class 'datetime.timedelta'>

所以,与其这样做:

new_time2 = timedelta(hours=starttime_time.hour+5, minutes=starttime_time.minute+30)

你必须:

delta = timedelta(hours=5, minutes=30)

new_time = starttime_time + delta

您可以将 time 实例转换为 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'>

那你可以比较一下:

>>> print(new_time2 >= e)
True

我用这个函数给时间对象加一分钟:

def addMinute(timeObject):
    # Python doesn't allow a time object to use timedelta
    # This function takes a time object converts it into a datetime object, adds 1 minute and returns a time object
    est_now_dt = datetime.now(est)
    #newDt = est_now_dt.replace(hour = timeObject.hour, minute = timeObject.minute, second = 0, microsecond = 0).time()
    newDt = est_now_dt.replace(hour = timeObject.hour, minute = timeObject.minute, second = 0, microsecond = 0)
    newDt = newDt + timedelta(minutes =1)
    newDt = newDt.time()
    return newDt