第一件事:
使用 .sleep() 作为计时器不是一个好主意。 Sleep() 没有考虑运行代码所需的时间。所以你实际上得到的不是一秒钟,而是code execution time + .sleep() + code execution time。这意味着如果将此代码发送给某人,它将根据他们的机器执行代码的速度进行不同的计算。
如果您有兴趣制作精确的内容,请查看this 和此线程。
至于我们的问题,您只需要格式化输出:
def countdown(t):
"""
Countdown Timer
"""
while t:
# Divmod takes only two arguments so
# you'll need to do this for each time
# unit you need to add
mins, secs = divmod(t, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
timer = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Fire in the hole!!')
t = 10
countdown(int(t))
这里是一个小例子,说明如果您测量很长一段时间,这些小差异会叠加起来。
import time
start_time = time.time()
def countdown(t):
"""
Countdown Timer
"""
while t:
# Divmod takes only two arguments so
# you'll need to do this for each time
# unit you need to add
mins, secs = divmod(t, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
timer = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, mins, secs)
print(timer, end="\r" )
time_before_sleep = time.time() - start_time
time.sleep(1)
time_after_sleep = time.time() - start_time
print(timer, time_before_sleep, time_after_sleep)
t -= 1
print('Fire in the hole!!')
t = 10
countdown(int(t))
输出:
00:00:09 1.0045790672302246 2.0046610832214355
00:00:08 2.0047121047973633 3.0048279762268066
00:00:07 3.0049359798431396 4.005050897598267
00:00:06 4.005151033401489 5.005663156509399
00:00:05 5.005772113800049 6.006514072418213
00:00:04 6.006554126739502 7.007684946060181
00:00:03 7.007725238800049 8.008012056350708
00:00:02 8.00806212425232 9.00907301902771
00:00:01 9.009180068969727 10.010266065597534