while True:
now = datetime.datetime.now();
if now.hour >= 22 and now.hour < 3:
print "sleep"
sleep_at = datetime.datetime.combine(datetime.date.today(),datetime.time(3))
sleep_til = (sleep_at - now).seconds
print sleep_til
time.sleep(sleep_til)
print "wake"
else:
print "break"
break
此代码应该让我的整个程序在晚上10点进入睡眠状态,并在凌晨3点起床。我的问题是......这会有用吗?我试过运行它..但我不能改变我的系统/电脑时间..所以我无法检查。 我发布此问题的原因是因为我的编码是使用datetime.date.tday和datetime.datetime来调用当前日期..
再次..我希望我的程序在晚上10点之前运行,晚上10点到凌晨3点之间睡觉,并在凌晨3点后重新运行..
有人可以检查这是否是正确的方法吗?
答案 0 :(得分:0)
考虑(为了清晰起见,详细说明):
import time, datetime
# Create time bounds -- program should run between RUN_LB and RUN_UB
RUN_LB = datetime.time(hour=22) # 10pm
RUN_UB = datetime.time(hour=3) # 3am
# Helper function to determine whether we should be currently running
def should_run():
# Get the current time
ct = datetime.datetime.now().time()
# Compare current time to run bounds
lbok = RUN_LB <= ct
ubok = RUN_UB >= ct
# If the bounds wrap the 24-hour day, use a different check logic
if RUN_LB > RUN_UB:
return lbok or ubok
else:
return lbok and ubok
# Helper function to determine how far from now RUN_LB is
def get_wait_secs():
# Get the current datetime
cd = datetime.datetime.now()
# Create a datetime with *today's* RUN_LB
ld = datetime.datetime.combine(datetime.date.today(), RUN_LB)
# Create a timedelta for the time until *today's* RUN_LB
td = ld - cd
# Ignore td days (may be negative), return td.seconds (always positive)
return td.seconds
while True:
if should_run():
print("--do something--")
else:
wait_secs = get_wait_secs()
print("Sleeping for %d seconds..." % wait_secs)
time.sleep(wait_secs)
但我确实认为睡觉不是延迟你的节目开始的最好方法。您可以查看Windows上的任务计划程序或Linux上的cron
。