Python 倒计时日期、小时、分钟和秒

rob*_*bel 2 python countdowntimer

在第二个例子的这个链接中,我找到了一个倒数计时器,但它只能在几分钟和几秒钟内工作,我怎样才能让它工作几小时和几天。这是代码

import time 

def countdown(t): 

    while t: 
        mins, secs = divmod(t, 60) 
        timer = '{:02d}:{:02d}'.format(mins, secs) 
        print(timer, end="\r") 
        time.sleep(1) 
        t -= 1

    print('Fire in the hole!!') 

t = 10

countdown(int(t))
Run Code Online (Sandbox Code Playgroud)

Geo*_*eom 5

第一件事:

使用 .sleep() 作为计时器不是一个好主意。Sleep() 不考虑运行代码所需的时间。所以,你在现实中得到什么不是一秒但code execution time+ .sleep()+ code execution 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.sleep(1) 
        t -= 1

    print('Fire in the hole!!') 

t = 10

countdown(int(t))
Run Code Online (Sandbox Code Playgroud)

这里是一个小问题演示,如果您测量很长一段时间,这些微小的差异会加起来。

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))
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)