我有一个启动主函数的代码。在这个函数中有一个while loop
,它应该在特定时间到来时启动程序。我在morning
(开始时间)和evening
(结束时间)变量中设置了这个时间。它是在while循环中运行的,但是只有在我想使用它的那一天启动这个程序的时候。例如:当我在星期一晚上(20:00)开始时,start
时间(morning
变量)是从8:00(第二天)开始的,它将继续循环
print("Waiting for the right time") <=(doing this)
即使第二天到了。但当我第二天6点左右开始的时候它就起作用了。。。你知道吗
有人能解释一下为什么会这样吗? 这是密码
import datetime
from time import sleep
from datetime import date
#variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=16, minute=15, second=0, microsecond=0)
#function for time-setting
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#main function
def main():
while True:
# Time period check
if date.today().weekday() < 5 and date.today().weekday() >= 0:
dayz = True
else:
dayz = False
if dayz != True:
print("Waiting for the day")
sleep(3600)
continue
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True: # HERE IT MAKES THE TROUBLE
print("Waiting for the right time")
sleep(200)
continue
print("do something")
main()
print("end of code")
当您调用
.replace()
来设置morning
和evening
时间时,它将当前日期作为datetime
对象的一部分。因此,如果您将其称为前一天,则日期将被设置为前一天的日期,因此.now()
永远不会位于前一天的时间范围之间。你知道吗例如,如果您在1月1日拨打set早晚电话,则存储的日期时间将为“1月1日上午8点”和“1月1日下午4点”。下次当你的循环检查时,它会问“是1月2日上午10点在1月1日上午8点到1月1日下午4点之间”,当然答案是否定的,因为1月1日是前一天。你知道吗
如果您只想检查时间,那么可能需要使用^{} 类而不是
datetime.datetime
类。或者,您可以将晚上和早上的datetimes的日期部分设置为您想要匹配的特定日期(但这对每周重复一次没有帮助)。你知道吗相关问题 更多 >
编程相关推荐