Skip to content
Advertisement

Python count down timer for date, hour, minute and second

In this link on the second example i found a count down timer, but it only works for minutes and seconds, how can i make it work for hours and days too. This is the code

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))

Advertisement

Answer

First things first:

Using .sleep() as a timer is not a good idea. Sleep() doesn’t take into consideration the time necessary to run the code. So what you’re in reality getting is not one second but code execution time + .sleep() + code execution time. This means that if send this code to someone it will calculate differently based on how fast their machine can execute the code.

If you’re interested in making precise content take a look at this and this thread.


As for our question you simply need to format the output:

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))

Here is a small demonstration of the problem these small differences will add up if you’re measuring a long period of time.

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))

output:

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement