Search code examples
pythontimercountdown

python 3.4, timer count down not working


I want to create a clock that count down in hours min and seconds, but for some reason is not working, can somebody help me

def countdown():
  times = 1
  th = 1
  tm = 0
  ts = 0
  while times != 0:
    if (ts>0 or tm>0 or th>0):
      print ('it run for ' + str(th) + ' Hours ' + str(tm) + ' Minutes ' + str(ts) + ' Seconds ')
      time.sleep(1)
      ts = ts - 1
      if (ts==0 and (tm>0 or th>0)):
        ts = 59
        tm = tm - 1
        if(ts==0 or tm==0 and th>0):
          ts = 59
          tm = 59
          th = th - 1
          if (ts==0 and tm==0 and th==0):          
            times = 0
  else:
    print ('stopped')
    ts = 0
    tm = 0
    th = 0

countdown()

thanks


Solution

  • A much simpler method is would be to use datetime and time.sleep

    In a function, where you can pass in days,hours,mins and seconds to countdown from:

    from datetime import datetime, timedelta
    import time
    
    def countdown(d=0, h=0, m=0, s=0):
        counter = timedelta(days=d, hours=h, minutes=m, seconds=s)
        while counter:
            time.sleep(1)
            counter -= timedelta(seconds=1)
            print("Time remaining: {}".format(counter))
    

    An example counting down 5 seconds:

    In [2]: countdown(s=5)
    Time remaining: 0:00:04
    Time remaining: 0:00:03
    Time remaining: 0:00:02
    Time remaining: 0:00:01
    Time remaining: 0:00:00
    

    Two hours:

    In [3]: countdown(h=2)
    Time remaining: 1:59:59
    Time remaining: 1:59:58
    Time remaining: 1:59:57
    Time remaining: 1:59:56
    Time remaining: 1:59:55
    Time remaining: 1:59:54