我的代码:
from datetime import datetime, date,time
timeobj = time(0, 5)
start = datetime.now().time()
time1 = datetime.combine(date.min, start) - datetime.combine(date.min, timeobj)
tx = start+time1 # throws error in here
if (start >= tx):
pass #do stuff
我遇到此错误:
TypeError:+不支持的操作数类型:“ datetime.time”和“ datetime.timedelta”
有人可以帮助我解决此问题吗?我只想使用上面的"if"
语句。
答案 0 :(得分:0)
这是我的建议:
from datetime import datetime, date, time
timeobj = time(0,5)
start = datetime.combine(date.min, datetime.now().time())
time1 = datetime.combine(date.min, start) - datetime.combine(date.min, timeobj)
tx = (start+time1).time()
if start.time() > tx:
pass # do stuff
答案 1 :(得分:0)
这里的问题是start
是datetime.time对象,time1
是两个datetime.datetimes之间的时间增量,因此+
运算符对于将它们组合起来没有意义。错误。
我不确定您要达到的目标,但总体来说,请确保您的start
变量属于可以添加timedelta的类型,例如:
from datetime import datetime, date,time
timeobj = time(0, 5)
start_time = datetime.now().time()
start = datetime.combine(date(1, 2, 3), start_time) # here start is a datetime object
time1 = datetime.combine(date.min, start_time) - datetime.combine(date.min, timeobj)
tx = start+time1
答案 2 :(得分:0)
不要太复杂,您只需要比较start和timeobj(5AM)。为什么?这是因为您只是在比较当前时间是否小于5AM。让我们做一些基本的代数。
given:
time1 = start - timeobj
tx = start + time1
thus: if (start >= tx) is the same with
start >= start + start - timeobj
0 >= start - timeobj
timeobj >= start
(is current time earlier than 5am?)
更新脚本:
from datetime import datetime, date,time
timeobj = time(0, 5)
start = datetime.now().time()
#time1 = datetime.combine(date.min, start) - datetime.combine(date.min, timeobj)
#tx = start+time1 # throws error in here
if (timeobj >= start ):
print('pass')
pass #do stuff