我正在尝试检查当前时间是否在某个时间段之间,在这种情况下介于10:00 pm至11:00 pm之间,但是遇到以下错误,如何解决此问题的任何指导?
import datetime
current_time = datetime.datetime.now().time()
if '22:00' <= current_time <= '23:00':
print "current time is between 10:00pm to 11:00pm"
else:
print "current time is NOT between 10:00pm to 11:00pm"
错误:-
Traceback (most recent call last):
File "datetime_script.py", line 4, in <module>
if '22:00' <= current_time <= '23:00':
TypeError: can't compare datetime.time to str
答案 0 :(得分:1)
使用current_time.hour
访问小时字段,该字段返回一个int
,这意味着不应将其与str
进行比较。
因此,您可以这样做:
import datetime
current_time = datetime.datetime.now().time()
if 22<= current_time.hour <=23:
print ("current time is between 10:00pm to 11:00pm")
else:
print ("current time is NOT between 10:00pm to 11:00pm")
答案 1 :(得分:0)
这将起作用。只需将其转换为字符串即可。
import datetime
current_time = datetime.datetime.now().time()
# use the str function
if '22:00' <= str(current_time) <= '23:00':
print ("current time is between 10:00pm to 11:00pm")
else:
print ("current time is NOT between 10:00pm to 11:00pm")
答案 2 :(得分:0)
您可以利用Python可以对Target: Container App
对象进行算术和比较这一事实。
您似乎只关心小时和分钟,因此只需从当前时间获取它们,以创建一个datetime
对象,然后将它们与表示22:00h和23:00h的类似对象进行比较。
datetime.time