提问人:Misbah Asif 提问时间:1/11/2022 更新时间:1/12/2022 访问量:695
如何在python中将timedelta对象与time对象进行比较
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'>
那么我有没有其他方法可以比较这两个时间。 提前致谢。
答:
0赞
Bhakta Raghavan
1/11/2022
#1
您创建了 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
1赞
babis21
1/11/2022
#2
您可以将实例转换为: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
0赞
Dan
1/12/2022
#3
我使用这个函数向时间对象添加一分钟:
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
评论