python 3.4,计时器倒计时不起作用

时间:2015-01-20 01:58:06

标签: python timer countdown

我想创建一个以小时和秒为单位倒数的时钟,但由于某些原因无法正常工作,有人可以帮助我吗

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

感谢

2 个答案:

答案 0 :(得分:4)

更简单的方法是使用datetimetime.sleep

在一个函数中,你可以在几天,几小时,几分钟和几秒内传递倒计时:​​

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

倒数5秒的示例:

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

两个小时:

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

答案 1 :(得分:2)

import datetime
import time

def countdown():
  count = datetime.timedelta(hours=1)
  while count:
    print ('it run for ' + str(count))
    time.sleep(1)
    count -= datetime.timedelta(seconds=1)

  print ('stopped')

countdown()