【发布时间】:2016-07-30 23:54:17
【问题描述】:
我在下面的代码中遇到问题,它要求用户输入“唤醒”时间,python 脚本随后将使用该时间来计算时钟到达零之前的时间。从下面的内容来看,我认为我需要将 tdelta 计算放在 while 循环中,以便它不断检查 当前 时间。
目前,tdelta 似乎会以秒为单位检查当前时间,然后使用相同的值运行 while 循环。因此永无止境,因为它一遍又一遍地使用相同的时间。我应该在 while 循环中使用 函数 来不断检查新值,然后评估 true 还是 false?
from datetime import datetime
import time
now = datetime.now()
hms = "%s:%s:%s" % (now.hour, now.minute, now.second)
ans = input('Enter hour:minute:seconds')
s1 = hms
s2 = ans # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
while tdelta.seconds != 0:
# Use this to see what is happening inside the loop. Here it continuously prints the same time in seconds so is a continuous loop. I need to somehow update the tdelta time.
if tdelta.seconds != 0:
print(tdelta.seconds)
time.sleep(1)
else:
print('time up...do something')
我已经尝试了上述代码的几十种变体,但都没有成功。我很感激任何提示。谢谢。
【问题讨论】:
-
需要在循环中更新,tdelta -= timedelta(seconds=1) 也需要导入 timedelta 后
-
也许您想使用调度程序? docs.python.org/3/library/sched.html
标签: function loops python-3.x date time