过去几天,我一直在尝试创建一个非常简单的计时器程序。 但是,我遇到了一个主要障碍,在运行程序时,第二个延迟倒计时只是被完全忽略了。 我尝试用time.sleep(1000)替换time.sleep(1),在它进入的while循环中重新排列它,但无济于事。该程序只是运行,在开始和循环中都没有延迟。
import time
hour, minute, second = 1, 2, 10
print("Starting now.")
x = 1
while x < 2:
print(str(hour) + ":" + str(minute) + ":" + str(second))
time.sleep(1)
second = second - 1
if second == 0:
minute = minute - 1
second = second + 60
if minute ==0:
hour = hour - 1
minute = minute + 60
if hour == 0:
x = x + 1
如果有人可以解决这个问题,那将是一个很大的帮助。谢谢!
答案 0 :(得分:0)
当其他人注释了原始问题中给出的代码后,它在正确配置的环境中正确休眠了,此答案使用datetime解决了时间处理中的逻辑问题。减去两个日期时间后的时间增量不会提供小时和分钟,因此它们是从秒计算得出的。
import time, datetime,math
d = datetime.timedelta(hours=1,minutes=2,seconds=10)
endtime = (datetime.datetime.now()+ d)
print("Starting now.")
while datetime.datetime.now().time() <endtime.time():
td = endtime - datetime.datetime.now()
print(str(math.floor(td.seconds / 3600)) + ":" +
str(math.floor(td.seconds / 60) - math.floor(td.seconds / 3600)*60 ) + ":" +
str(td.seconds - math.floor(td.seconds / 60)*60) )
time.sleep(1)
您还可以按照以下方式纠正原始逻辑
import time
hour, minute, second = 1, 2, 10
print("Starting now.")
x = 1
while x < 2:
print(str(hour) + ":" + str(minute) + ":" + str(second))
time.sleep(1)
second = second - 1
if second < 0:
minute = minute - 1
if minute >= -1:
second = second + 60
if minute < 0:
hour = hour - 1
if hour >= 0:
minute = minute + 60
if hour <= 0 and minute <= 0 and second <= 0:
x = x + 1