Search code examples
pythonpython-3.xloopstimercountdown

How to loop my countdown timer in Python?


I'm trying to loop my timer, so it would show me how many seconds are left. Right now it only shows me how many seconds are left from the moment of starting a script, but I would like it to change every second. I'm going to run this script 24/7, so I need real time result.

My timer:

from datetime import datetime
from threading import Timer
import time


x = datetime.now()
y=x.replace(hour=12, minute=0, second=0)
t=y-x
secs=t.seconds

I was thinking about while loop, but I don't know how to use it in this code. If you want you can change my timer I only want it to tell me how many seconds are left to designated time.

How I solved it:

from datetime import datetime
from threading import Timer
import time


while True:
    time.sleep(1)
    x=datetime.today()
    y=x.replace(hour=17, minute=10, second=0)
    t=y-x
    secs=t.seconds

Solution

  • import time, datetime
    
    designated_date = datetime.datetime(2021, 1, 6, 15, 8, 24) # designated_date
    designated_time = time.mktime(designated_date.timetuple()) # designated unix time in seconds
    
    while True:
        time.sleep(1)         # 1 second delay
        current_time = int(time.time())      # every second get current unix time
        left = designated_time - current_time # calculation how much seconds left to desingated time
        print(left) # print results