Python time.sleep() 在定时器程序中被忽略

Python time.sleep() being ignored in timer program

过去几天我一直在尝试创建一个极其简单的计时器程序。 但是,我遇到了一个主要障碍,其中在 运行 程序时完全忽略了第二次延迟倒计时。 我尝试用 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

如果有人能解决这个问题,那将是一个很大的帮助。谢谢!

正如其他人评论的那样,原始问题中给出的代码确实在正确配置的环境中正确睡眠,这个答案通过使用日期时间解决了时间处理中的逻辑问题。减去两个日期时间的 timedelta 不提供小时和分钟,因此这些是根据秒计算的。

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