How to make a timer program in Python

Here is my goal: to make a small program (text) that starts with a greeting, print a timer for how long it has been since the last event, and then a timer for the event. I used this code to start by trying to figure out a timer, but my first problem is that the timer keeps repeating on a new line with every new second. How can I stop this? In addition, this timer seems to lag behind the 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
+5
source share
8 answers

I would say 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 rely on the actual time module, and not just on the increment of sleep mode, since sleep will not be exactly 1 second.

, print sys.stdout.write, sys.stdout.flush.

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

, .

+3

. .

     # 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
+2

(Windows 7) cmd , . , , os.system ('cls') - , , , Windows?

while s<=60: , s 60 - , 60, reset 0 m. , while m<60:?

, . - .. while, time.sleep(1), , , ( - ) 0,1 (), 10% . @sberry .

0

, , .

, , time.sleep() "" 1 , . , , , 1s + Xs. , , .

, , print() , , .

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

, end="YourThing" :

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

,

"TestTestTest"

, -

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

timeit . time.sleep(x) . , :

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)

, , time.sleep, 1 . 1 . , :

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

, 2, , . timerLoop time.sleep():

time.sleep(timerLoop)

.

0
# 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\ 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 version. You can set the duration and it will beep after the specified duration, similar to the version of Force Fighter

0
source

It seems to be a lot 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))
-1
source

A simple timer program that has a sound reminding you will 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. It is converted every 60 seconds per minute. sound works only with Windows or you can install pygame to add sounds.

-1
source

All Articles