简体   繁体   English

如何在 Python 中制作计时器程序

[英]How to make a timer program in Python

Here is my goal: To make a small program (text based) that will start with a greeting, print out a timer for how long it has been since the last event, and then a timer for the event.这是我的目标:制作一个以问候语开头的小程序(基于文本),打印出自上次事件以来已经过去了多长时间的计时器,然后打印出事件的计时器。 I have used this code to start out with trying to figure out a timer, but my first problem is that the timer keeps repeating on a new line with each new second.我已经使用此代码开始尝试找出一个计时器,但我的第一个问题是计时器每增加一秒就会在新行上不断重复。 How do I get that to stop?我怎样才能让它停止? Also, this timer seems to lag behind actual seconds on the clock.此外,这个计时器似乎落后于时钟上的实际秒数。

import os
import time


s=0
m=0

while s<=60:
    os.system('cls')
    print (m, 'Minutes', s, 'Seconds')
    time.sleep(1)
    s+=1
    if s==60:
        m+=1
        s=0

I would go with something like this:我会用这样的东西:

import time
import sys

time_start = time.time()
seconds = 0
minutes = 0

while True:
    try:
        sys.stdout.write("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
        sys.stdout.flush()
        time.sleep(1)
        seconds = int(time.time() - time_start) - minutes * 60
        if seconds >= 60:
            minutes += 1
            seconds = 0
    except KeyboardInterrupt, e:
        break

Here I am relying on actual time module rather than just sleep incrementer since sleep won't be exactly 1 second.在这里,我依赖于实际时间模块,而不仅仅是睡眠增量器,因为睡眠不会正好是 1 秒。

Also, you can probably use print instead of sys.stdout.write , but you will almost certainly need sys.stdout.flush still.此外,您可能可以使用print而不是sys.stdout.write ,但您几乎肯定仍然需要sys.stdout.flush

Like:喜欢:

print ("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds)),

Note the trailing comma so a new line is not printed.请注意尾随逗号,因此不会打印新行。

This is my version.这是我的版本。 It's great for beginners.这对初学者来说很棒。

     # Timer
import time
print("This is the timer")
# Ask to Begin
start = input("Would you like to begin Timing? (y/n): ")
if start == "y":
    timeLoop = True

# Variables to keep track and display
Sec = 0
Min = 0
# Begin Process
timeLoop = start
while timeLoop:
    Sec += 1
    print(str(Min) + " Mins " + str(Sec) + " Sec ")
    time.sleep(1)
    if Sec == 60:
        Sec = 0
        Min += 1
        print(str(Min) + " Minute")
# Program will cancel when user presses X button

On my PC (Windows 7) when run in a cmd window, this program works almost exactly as you say it should.在我的 PC (Windows 7) 上,当在cmd窗口中运行时,该程序几乎完全按照您说的那样工作。 If the timer is repeating on a new line with each second, that suggests to me that os.system ('cls') is not working for you -- perhaps because you're running on an OS other than Windows?如果计时器每秒在新行上重复一次,这向我表明os.system ('cls')对您不起作用——也许是因为您在 Windows 以外的操作系统上运行?

The statement while s<=60: appears to be incorrect because s will never be equal to 60 in that test -- anytime it gets to 60, it is reset to 0 and m is incremented.语句while s<=60:似乎是不正确的,因为在该测试中s永远不会等于 60——只要它达到 60,它就会重置为 0 并且m递增。 Perhaps the test should be while m<60: ?也许测试应该是while m<60:

Finally, on my PC, the timer does not appear to lag behind actual seconds on the clock by much.最后,在我的 PC 上,计时器似乎并没有落后于时钟上的实际秒数。 Inevitably, this code will lag seconds on the clock by a little -- ie however long it takes to run all the lines of code in the while loop apart from time.sleep(1) , plus any delay in returning the process from the sleeping state.不可避免地,这段代码会在时钟上稍微滞后几秒——也就是说while除了time.sleep(1)之外,运行while循环中的所有代码行需要多长时间,加上从睡眠状态返回进程的任何延迟状态。 In my case, that isn't very long at all but, if running that code took (for some reason) 0.1 seconds (for instance), the timer would end up running 10% slow compared to wall clock time.就我而言,这根本不是很长,但是,如果运行该代码需要(出于某种原因)0.1 秒(例如),则与挂钟时间相比,计时器的运行速度最终会慢 10%。 @sberry's answer provides one way to deal with this problem. @sberry 的回答提供了一种处理这个问题的方法。

Ok, I'll start with why your timer is lagging.好的,我将从为什么您的计时器滞后开始。

What happens in your program is that the time.sleep() call "sleeps" the program's operation for 1 second, once that second has elapsed your program begins execution again.在您的程序中发生的是time.sleep()调用“休眠”程序的操作 1 秒,一旦该秒过去,您的程序将再次开始执行。 But your program still needs time to execute all the other commands you've told it to do, so it takes 1s + Xs to actually perform all the operations.但是您的程序仍然需要时间来执行您告诉它执行的所有其他命令,因此实际执行所有操作需要1s + Xs Although this is a very basic explanation, it's fundamentally why your timer isn't synchronous.尽管这是一个非常基本的解释,但从根本上说,这就是您的计时器不同步的原因。

As for why you're constantly printing on a new line, the print() function has a pre-defined end of line character that it appends to any string it is given.至于为什么你总是在新行上print()print()函数有一个预定义的行尾字符,它附加到它给定的任何字符串。

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

You can overwrite this with anything by putting end="YourThing" in your print statement like so您可以通过在打印语句中添加end="YourThing"来覆盖它,如下所示

for x in range(3):
    print("Test", end="")

The above example appends an empty string to the end of the line, so the output of the loop would be上面的例子在行尾附加了一个空字符串,所以循环的输出将是

"TestTestTest"

As for solving your timer problem, you should use something similar to至于解决您的计时器问题,您应该使用类似于

timePoint = time.time()

while True:

    #Convert time in seconds to a gmtime struct
    currentTime = time.gmtime(time.time() - timePoint))

    #Convert the gmtime struct to a string
    timeStr = time.strftime("%M minutes, %S seconds", currentTime)

    #Print the time string
    print(timeStr, end="")

Use the timeit module to time your code.使用 timeit 模块为您的代码计时。 Then adjust the time.sleep(x) accordingly.然后相应地调整 time.sleep(x)。 For example, you could use one of the following:例如,您可以使用以下方法之一:

import timeit
#Do all your code and time stuff and while loop
#Store that time in a variable named timedLoop
timer = 1- timedLoop

#Inside while loop:
   time.sleep(timer)

This will time the code you have other than the time.sleep, and subtract that from 1 second and will sleep for that amount of time.这将对您除 time.sleep 以外的代码进行计时,并将其从 1 秒中减去,然后睡眠这段时间。 This will give an accurate representation of 1 second.这将给出 1 秒的准确表示。 Another way is less work, but may not be as accurate:另一种方法是更少的工作,但可能不那么准确:

#set up timeit module in another program and time your code, then do this:
#In new program:
timer = 1 - timerLoop
print timerLoop

Run your program, then copy the printed time and paste it into program two, the one you have now.运行您的程序,然后复制打印的时间并将其粘贴到程序二中,即您现在拥有的程序。 Use timerLoop in your time.sleep():在 time.sleep() 中使用 timerLoop:

time.sleep(timerLoop)

That should fix your problem.那应该可以解决您的问题。

# Timer
import time
import winsound
print "               TIMER"
#Ask for Duration
Dur1 = input("How many hours?  : ")
Dur2 = input("How many minutes?: ")
Dur3 = input("How many seconds?: ")
TDur = Dur1 * 60 * 60 + Dur2 * 60 + Dur3
# Ask to Begin
start = raw_input("Would you like to begin Timing? (y/n): ")
if start == "y":
    timeLoop = True

# Variables to keep track and display
CSec = 0
Sec = 0
Min = 0
Hour = 0
# Begin Process
timeLoop = start
while timeLoop:
    CSec += 1
    Sec += 1
    print(str(Hour) + " Hours " + str(Min) + " Mins " + str(Sec) + " Sec ")
    time.sleep(1)
    if Sec == 60:
        Sec = 0
        Min += 1
        Hour = 0
        print(str(Min) + " Minute(s)")
    if Min == 60:
        Sec = 0
        Min = 0
        Hour += 1
        print(str(Hour) + " Hour(s)")
    elif CSec == TDur:
        timeLoop = False
        print("time\'s up")
        input("")
    while 1 == 1:
        frequency = 1900  # Set Frequency To 2500 Hertz
        duration = 1000  # Set Duration To 1000 ms == 1 second
        winsound.Beep(frequency, duration)

I based my timer on user5556486's version.我的计时器基于 user5556486 的版本。 You can set the duration, and it will beep after said duration ended, similar to Force Fighter's version您可以设置持续时间,持续时间结束后会发出哔哔声,类似于Force Fighter的版本

# This Is the Perfect Timer!(PS: This One Really Works!)
import sys
import time
import os

counter=0
s = 0
m = 0
n = int(input("Till How Many Seconds do you want the timer to be?: "))
print("")

while counter <= n:
    sys.stdout.write("\x1b[1A\x1b[2k")
    print(m, 'Minutes', s, 'Seconds')
    time.sleep(1)
    s += 1
    counter+=1
    if s == 60:
        m += 1
        s = 0

print("\nTime Is Over Sir! Timer Complete!\n")

The ideas are pretty cool on other posts -- however, the code was not useable for what I wanted to do.这些想法在其他帖子中非常酷——但是,代码无法用于我想做的事情。

I liked how people want to subtract time, in this way you don't have to have a time.sleep()我喜欢人们想要减去时间的方式,这样你就不必有 time.sleep()

from datetime import datetime

timePoint = time.time()
count = 0
while (count < 10):
    timePoint2 = time.time()
    timePointSubtract = timePoint2 - timePoint
    timeStamp1 = datetime.utcfromtimestamp(timePointSubtract).strftime('%H:%M:%S')
    print(f'{count} and {timeStamp1}')
    val = input("")
    count = count + 1

So, pretty much I wanted to have a timer but at the same time keep track of how many times I pressed enter.所以,我很想有一个计时器,但同时要跟踪我按 Enter 的次数。

Here my answer.这是我的答案。

import time
import sys

time_start = time.time()

hours = 0
seconds = 0
minutes = 0

while True:

    sys.stdout.write("\r{hours} Hours {minutes} Minutes {seconds} Seconds".format(hours=hours, minutes=minutes, seconds=seconds))
    sys.stdout.flush()
        
    if (seconds <= 59):
        time.sleep(1)
        seconds += 1

        if (minutes <= 59 and seconds == 59 + 1):
            minutes += 1

            if (minutes == 60 and seconds == 59 + 1 ):
                hours += 1
                minutes = 0
                seconds = 0

    else:
        seconds = 0

This seems like it would be MUCH easier:这似乎会容易得多:

#!/usr/bin/env python
from datetime import datetime as dt
starttime = dt.now()
input("Mark end time")
endtime = dt.now()
print("Total time passed is {}.".format(endtime-starttime))

a simple timer program that has sound to remind you would be:一个有声音提醒你的简单定时器程序是:

from time import sleep
import winsound
m = 0
print("""**************************
Welcome To FASTIMER®
**************************""")
while True:
    try:
        countdown = int(input("How many seconds:  "))
        break
    except ValueError:
        print("ERROR, TRY AGAIN")
original = countdown
while countdown >= 60:
    countdown -= 60
    m += 1
for i in range (original,0,-1):
    if m < 0:
        break
    for i in range(countdown,-2,-1):
        if i % 60 == 0:
            m-=1
        if i == 0:
            break
        print(m," minutes and ",i," seconds")
        sleep(1)
    if m < 0:
        break
    for j in range(59,-1,-1):
        if j % 60 == 0:
            m-=1          
        print(m," minutes and ",j," seconds")
        sleep(1)
print("TIMER FINISHED")
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

this program uses time.sleep() to wait a second.该程序使用 time.sleep() 等待一秒钟。 It converts every 60 seconds to a minute.它每 60 秒转换为一分钟。 the sound only works with Windows or you can install pygame to add sounds.声音仅适用于 Windows,或者您可以安装 pygame 来添加声音。

I have a better way:我有一个更好的方法:

import time
s=0
m=0
while True:
  print(m,  'minutes,', s, 'seconds')
  time.sleep(0.999999999999999999999) # the more 9s the better
  s += 1
  if s == 60:
    s=0
    m += 1

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

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