我正在创建一个循环,每5秒执行一次,从startTime变量开始,到stopTime变量结束。但是,下面的代码忽略了我的startTime和endTime变量中的分钟,并且只在小时执行。例如,即使我的startTime是'1130',代码也执行11:05,而不是结束循环。我对endTime变量有同样的问题。如果当前时间是12:45,即使endTime变量为'1230',代码仍会执行。代码将在'1300'处停止执行。
frequency = 5
startTime = '1130'
endTime = '1230'
while True:
now = datetime.now().strftime('%H:%M:%S')
if startTime <= now <= endTime:
print('Loop is working. Time is: ',now)
time.sleep(frequency)
else:
print('Loop is stopped')
break
我住在中部时间,所以我尝试通过将“now”变量修改为:切换到东部时区:
now = datetime.now(timezone('US/Eastern')).strftime('%H:%M:%S.%f %Z')
但是当我用东方datetime.now()替换东部时间和startTime时,我仍然会遇到同样的问题。
是否可以使用strftime()以精确的分钟执行代码?
编辑:(这是现实问题的答案(哎呀))
如果您想等到例如11:30(这是真正的问题),您可以计算程序应该睡眠的时间(以秒为单位)(让它在那段时间内睡觉):
def wait_till(hour, minute, second=0):
# get system time (and date)
now_time = datetime.datetime.now()
# create time point we are waiting for (this year, this month and this day)
wait_till_time = datetime.datetime(year=now_time.year, month=now_time.month, day=now_time.day, hour=hour, minute=minute, second=second)
# calculate time we want to wait for and convert to seconds
wait_for = (wait_till_time - now_time).total_seconds()
# check if it's going to be tomorrow (if we would sleep for a negative amount of seconds)
if wait_for < 0:
# add one day
wait_till_time = wait_till_time.replace(day=now_time.day+1)
# recalculate (not very beautiful, but i don't know a better way)
wait_for = (wait_till_time - now_time).total_seconds()
# printing this waiting time (in seconds)
print("waiting for",wait_for,"seconds")
# sleeping for that time
time.sleep(wait_for)
# printing the new now time, so we can see how accurate it is
print("its now",datetime.datetime.now())
并说例如:
wait_till(20, 24) # waiting till 20:24 (today)
得到:
waiting for 15.32297 seconds
its now 2019-03-11 20:24:00.003857
这非常接近我们想要的(20:24:00.000000),这种延迟可能只是由格式化字符串的计算延迟引起的。
(旧东西......)
如果它不是很重要,它需要100%5s(而不是100.04546642303467% - >它会每次都有点下降)你可以做
import time
frequency = 5 #every 5 seconds
start_time = time.time()
while 1:
elspsed_time = time.time() - start_time
print(elspsed_time)
time.sleep(frequency)
但如果您需要100%,您可以尝试这种自动修正解决方案:
import time
from threading import Timer
frequency = 5 #every 5 seconds
start_time = time.time()
def what_to_do_after_5s():
elapsed_time = time.time() - start_time
print(elapsed_time)
# next call
Timer(5.0 - (elapsed_time - int(elapsed_time)), what_to_do_after_5s, ()).start()
what_to_do_after_5s()
我们可以看到它自动修正:
0.0
5.000170707702637
10.000272989273071
15.000539064407349
20.001248836517334
25.00046443939209
30.000929355621338
35.00142860412598
40.0007688999176
45.00128436088562
50.00045442581177
55.000683069229126
60.00123882293701
65.00095415115356
70.0015127658844