【发布时间】:2019-08-30 04:34:06
【问题描述】:
我正在编写一个程序,如果now == specific time and day 会做一些事情,如果不相等则等到那个时间。
我有一个morning、evening、days 值,它显示开始时间、结束时间和今天。我想制作一个程序来检查今天是否是工作日和特定时间(在morning 和evening 之间)如果True 做某事,如果其中一个是False,我会等到那个时间然后做一些事情。
我是用while loop 完成的,但是当它以False 值开始时(不是在正确的时间),它会继续打印False,即使那个时间到了并且值应该更改为True,但它显示True当我在正确的时间启动它时。
代码如下:
import datetime
from datetime import date
from time import sleep
#setting values
now = datetime.datetime.now()
morning = now.replace(hour=9, minute=00, second=0, microsecond=0)
evening = now.replace(hour=16, minute=0, second=0, microsecond=0)
days = now.strftime("%A")
#check if time is in range and return True or False
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)
#check if today is weekday
if date.today().weekday() == 0:
dayz = True
else:
dayz = False
# If today weekday and time range do something
if dayz == True and timerange == True:
print("Yes")
while dayz == False or timerange == False:
sleep(5)
timerange = time_in_range(morning, evening, now)
print(timerange) #this printing false even if is right time.
# But it shows True when I turn it on in right time
【问题讨论】:
-
sleep(5)你确定你需要 5 秒。准确性?你真的需要等待时间的到来吗?为什么不使用 cron 在给定时间启动您的脚本 -
不是循环休眠,而是计算下一个时间范围开始之前的秒数,然后休眠那么多秒。
标签: python python-3.x time