如何创建一个倒数的Python计时器?

时间:2020-07-28 17:05:38

标签: python

我的代码:

def timer():
    while True:
        try:
           when_to_stop = 90
        except KeyboardInterrupt:
             break
        except:
             print("error, please star game again")
        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + 
            str(s).zfill(2) # got cut off, belongs to the line before this
            print("time:", time_left + "\r", end="")
            if time_left == 0:
               print("TIME IS UP!")
            time.sleep(1)
        when_to_stop -= 1

这工作得很好,除了time.sleep意味着我的整个程序都处于睡眠状态,因此之后的所有内容都会停止90秒。有什么方法可以解决这个问题?(或在没有时间的情况下建立新的计时器。)

1 个答案:

答案 0 :(得分:2)

我认为,或者,您可以跟踪计时器的启动时间,并通过查看经过的时间是否长于计时器应该持续的时间来检查时间。我不确定您对Python中的类和对象了解多少,但这是我想到的解决方案:

import datetime

class Timer:
  def __init__(self,**kwargs):
      self.start = datetime.datetime.now()
      self.length = datetime.timedelta(**kwargs)
      self.end = self.start+self.length
  def isDone(self):
      return (self.end-datetime.datetime.now()).total_seconds()<=0
  def timeLeft(self):
      return self.end-datetime.datetime.now()
  def timeElapsed(self):
      return datetime.datetime.now()-self.start

即使您不太了解类本身,如果将其放在代码中,它也应该像魅力一样工作:

#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)

while(not t.isDone()):
  #Do other game stuff here....
    time_left = t.timeLeft()
    print(f"time: {time_left}")
    #And here....
print("Done now")