【发布时间】:2021-03-03 16:10:50
【问题描述】:
我有一个函数,我需要每天从下午 5 点运行到第二天早上 9 点,然后在下午 5 点重新开始。下面是我的实现:
import datetime as dt
import time
while True:
if dt.datetime.now().hour < 9 or dt.datetime.now().hour > 17:
#some irrelevant function here
print('Function processing')
time.sleep(1)
else:
print("Not time yet")
time.sleep(1)
continue
上面的代码有效,但我还想在下午 5 点的每个第一个循环和上午 9 点的最后一个循环之后执行一次函数。我的第一直觉是做这样的事情:
def starting(): print("It's 9pm, time to start!")
def ending(): print("It's 5am, time to end")
while True:
if dt.datetime.now().hour < 9 or dt.datetime.now().hour > 17:
if #this is the first loop since 5pm:
starting()
elif #this is the last loop at 9am:
ending()
#some irrelevant function here
print('Function processing')
time.sleep(1)
else:
print("Not time yet")
time.sleep(1)
continue
我不确定这是否是最好的方法,希望能有一些想法。
【问题讨论】:
-
抱歉,我使用的是 Windows,我更喜欢 Jupyter Notebook 等 IDE 中的解决方案。
-
您的函数将在下午 6 点运行,而不是下午 5 点。
标签: python loops datetime if-statement while-loop