Python Forum

Full Version: How do I create a timer that counts down?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Could some one tell me how to make a timer that counts down? I have no problem making one that counts up, but I am at a loss with trying to figure out how to make one count down. To start I create a list of numbers.
time = [2,0,0,0]
This represents 20:00.(I combine all the numbers in to one string and display it as text. I can't figure out how to make it count down. If I were to make it count up I would do this.
           time[3] += 1
           if time[3] == 10:
               time[2] += 1
               time[3] = 0
           if time[2] == 6:
               time[1] += 1
               time[2] = 0
           if time[1] == 10:
               time[0] += 1
               time[1] = 0
I have this in a loop that runs once every second. Then when time[0] == 6 I just stop the loop. But How would I make a timer that counts down?
Just use the datetime module:

from datetime import datetime,timedelta
import time

start = "20:00:00"
dt = datetime.strptime(start,"%H:%M:%S")
while True:
    print(dt.time())
    dt = dt - timedelta(seconds=1)
    time.sleep(1)
Subtract one from the smallest unit. If that results in -1, set that unit to the max, and subtract one from the next highest unit. When it's all zeros, you're done.
time[3] -= 1
if time[3] < 0:
    time[3] = 9
    time[2] -= 1
if time[2] < 0:
    time[2] = 5
    time[1] -= 1
if time[1] < 0:
    time[1] = 9
    time[0] -= 1
if time[0] < 0:
    time[0] = 2
    time[1] = 3
Thank you.