Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a timer program in Python

Tags:

python

timer

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
like image 739
Erich Von Hinken Avatar asked Apr 04 '13 04:04

Erich Von Hinken


People also ask

How does timer work in Python?

Python timer functionsAfter every specified number of seconds, a timer class function is called. start() is a function that is used to initialize a timer. To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class.

What is countdown timer in Python?

Countdown time in PythonThe divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder. end='\r' overwrites the output for each iteration. The value of time_sec is decremented at the end of each iteration.


1 Answers

# 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. You can set the duration, and it will beep after said duration ended, similar to Force Fighter's version

like image 195
TMagnetB Avatar answered Oct 15 '22 13:10

TMagnetB