【问题标题】:Creating a timer in python在python中创建一个计时器
【发布时间】:2013-08-26 16:50:49
【问题描述】:
import time
def timer():
   now = time.localtime(time.time())
   return now[5]


run = raw_input("Start? > ")
while run == "start":
   minutes = 0
   current_sec = timer()
   #print current_sec
   if current_sec == 59:
      mins = minutes + 1
      print ">>>>>>>>>>>>>>>>>>>>>", mins

我想创建一种秒表,当分钟达到20分钟时,会弹出一个对话框,对话框不是问题。但是我的分钟变量在这段代码中没有增加。

【问题讨论】:

标签: python time


【解决方案1】:

从线程中查看Timer Objects

怎么样

from threading import Timer

def timeout():
    print("Game over")

# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()

# wait for time completion
t.join()

如果您想将参数传递给timeout 函数,您可以在计时器构造函数中给它们:

def timeout(foo, bar=None):
    print('The arguments were: foo: {}, bar: {}'.format(foo, bar))

t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})

也可以使用functools.partial创建绑定函数,也可以传入实例绑定方法。

【讨论】:

  • 为什么我需要“time.sleep(1500)”
  • 这是一个示例,这样您的主服务器就不会立即退出:D
  • 在 gui 应用程序中,您只需继续您的主循环。
  • 好的,所以您的代码意味着当 t 启动时,它会在该时间间隔内执行超时函数中的任何内容?
  • 超时函数20分钟后执行一次。
【解决方案2】:

你真的可以通过使用time.sleep来简化整个程序:

import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
    # Loop until we reach 20 minutes running
    while mins != 20:
        print(">>>>>>>>>>>>>>>>>>>>> {}".format(mins))
        # Sleep for a minute
        time.sleep(60)
        # Increment the minute total
        mins += 1
    # Bring up the dialog box here

【讨论】:

  • time.sleep 有什么作用?
  • @user2711485 - 无论您告诉它多少秒,它都会暂停计算机(在本例中为 60,即一分钟)。换句话说,它的意思是“在这个时间用完之前什么都不做”。
  • 在使用 time.sleep() 时是否可以运行其他代码,例如,如果您正在制作游戏,计时器是否可以在后台运行,或者在调用 time.sleep() 时一切都会停止?
  • @Qwertieϟ - 一切都将暂停,直到对 time.sleep 的调用结束。这就是time.sleep的目的:让程序停止执行一段时间。
  • @Qwertieϟ - 为此使用Timer objects。或者一般的 threading 库。
【解决方案3】:

我会使用 timedelta 对象。

from datetime import datetime, timedelta

...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
    if next_time <= datetime.now():
        minutes += 1
        next_time += period

【讨论】:

  • 虽然这可行,但不断运行 while 循环会消耗大量处理能力。添加一个睡眠时间(即使只有一秒钟)可以大大减少这种使用。
  • 当然。 Busy waiting 循环“被认为是一种反模式,应该避免,因为可用于执行不同任务的处理器时间反而浪费在无用的活动上。”
【解决方案4】:

您的代码很完美,只是您必须进行以下替换:

minutes += 1 #instead of mins = minutes + 1

minutes = minutes + 1 #instead of mins = minutes + 1

但这是解决此问题的另一种方法:

def wait(time_in_seconds):
    time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)

【讨论】:

    【解决方案5】:
    mins = minutes + 1
    

    应该是

    minutes = minutes + 1
    

    还有,

    minutes = 0
    

    需要在 while 循环之外。

    【讨论】:

    • 此外,如果您要坚持使用此代码,minutes = 0 需要位于 while 循环之外。但实际上,他可能应该只使用更适合这项任务的东西。
    • minutes += 1 怎么样?
    【解决方案6】:

    我想创建一种秒表,当分钟达到 20 分钟时,会弹出一个对话框

    你只需要在指定的时间睡觉。 time.sleep() 需要几秒钟才能进入睡眠,所以 20 * 60 是 20 分钟。

    import time
    run = raw_input("Start? > ")
    time.sleep(20 * 60)
    your_code_to_bring_up_dialog_box()
    

    【讨论】:

      【解决方案7】:
      # this is kind of timer, stop after the input minute run out.    
      import time
      min=int(input('>>')) 
      while min>0:
          print min
          time.sleep(60) # every minute 
          min-=1  # take one minute 
      

      【讨论】:

      • 希望我拙劣的语言能有所帮助
      【解决方案8】:
      import time 
      
      ...
      
      def stopwatch(mins):
         # complete this whole code in some mins.
         time.sleep(60*mins)
      
      ...
      

      【讨论】:

        【解决方案9】:
        import time
        mintt=input("How many seconds you want to time?:")
        timer=int(mintt)
        while (timer != 0 ):
            timer=timer-1
            time.sleep(1)
            print(timer)
        

        这项工作非常适合计时秒数。

        【讨论】:

          【解决方案10】:

          【讨论】:

          • 如果计时器对象触发的动作不平凡,那么使用计时器对象可能会变得很棘手。如果使用计时器,则必须处理线程同步问题。
          【解决方案11】:

          试着让你的 while 循环像这样:

          minutes = 0
          
          while run == "start":
             current_sec = timer()
             #print current_sec
             if current_sec == 59:
                minutes = minutes + 1
                print ">>>>>>>>>>>>>>>>>>>>>", mins
          

          【讨论】:

            【解决方案12】:
            import time
            def timer(n):
                while n!=0:
                    n=n-1
                    time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
                    print "00 : ",n
            timer(30) #here you can change n according to your requirement.
            

            【讨论】:

              【解决方案13】:
              import time
              def timer():
                 now = time.localtime(time.time())
                 return now[5]
              
              
              run = raw_input("Start? > ")
              while run == "start":
                 minutes = 0
                 current_sec = timer()
                 #print current_sec
                 if current_sec == 59:
                    mins = minutes + 1
                    print ">>>>>>>>>>>>>>>>>>>>>", mins
              

              实际上我自己正在寻找一个计时器,而您的代码似乎可以工作,您的分钟数未被计算的可能原因是当您这么说时

              分钟 = 0

              然后

              分钟 = 分钟 + 1

              和说的一样

              分钟 = 0 + 1

              我敢打赌,每次打印分钟时,它都会显示“1”,因为我刚刚解释过,“0+1”总是会导致“1”。

              你首先要做的是把你的

              分钟 = 0

              while 循环之外的声明。之后就可以删除了

              分钟 = 分钟 + 1

              行,因为在这种情况下您实际上不需要另一个变量,只需将其替换为

              分钟 = 分钟 + 1

              这样分钟会以“0”值开始,接收新值“0+1”,接收新值“1+1”,接收新值“2+1”,等等

              我意识到很多人已经回答了它,但我认为它会有所帮助,明智地学习,如果你能看到你犯的错误并尝试修复它。希望它有所帮助。另外,谢谢你的计时器。

              【讨论】:

                【解决方案14】:
                from datetime import datetime
                now=datetime.now()
                Sec=-1
                sec=now.strftime("%S")
                SEC=0
                while True:
                    SEC=int(SEC)
                    sec=int(sec)
                    now=datetime.now()
                    sec=now.strftime("%S")
                    if SEC<sec:
                        Sec+=1
                    SEC=sec
                print(Sec) #the timer is Sec
                

                【讨论】:

                • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                猜你喜欢
                • 2012-10-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-04-09
                相关资源
                最近更新 更多