How to make a timer program in Python

前端 未结 11 2223
予麋鹿
予麋鹿 2021-02-08 14:24

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

相关标签:
11条回答
  • 2021-02-08 14:58

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

    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.

    0 讨论(0)
  • 2021-02-08 15:03

    Use the timeit module to time your code. Then adjust the time.sleep(x) accordingly. 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. This will give an accurate representation of 1 second. 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)
    

    That should fix your problem.

    0 讨论(0)
  • 2021-02-08 15:04

    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
    
    0 讨论(0)
  • 2021-02-08 15:07

    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))
    
    0 讨论(0)
  • 2021-02-08 15:08
    # 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")
    
    0 讨论(0)
  • 2021-02-08 15:12

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

    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="")
    
    0 讨论(0)
提交回复
热议问题