简体   繁体   English

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

[英]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 谢谢

A much simpler method is would be to use datetime and time.sleep 一个简单得多的方法是使用datetimetime.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: 倒数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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM