Timer implementation in python - python

I'm trying to implement a timer that counting down hours, mins and secs. I saw a similar implementation on the internet but still yet, there is nothing that printed to the terminal:
import time
time_to_wait = 30
while time_to_wait:
seconds = time_to_wait % 60
mins = time_to_wait // 60
hours = mins * 60
timer = '{:02d}:{:02d}:{:02d}'.format(hours, mins, seconds)
print(timer, end="\r")
time.sleep(1)
time_to_wait -= 1

print(timer, end="\r")
\r denotes carriage return so timer is printed and then (very quickly) wiped, to avoid that you should print carriage return first, that is please try using
print("\r", timer, end="")

Related

Creating a timer for powerups in a game loop?

Hi I am trying to add a timer to my power up in the game. In space invaders, when the core hits 500 I added it so that you gain an extra gun, but this is infinite and I only want to it to go for ten seconds. I tried the threading library which didn't work for e with object oriented programming, any suggestions?
You can try this:
import time
time_in_seconds = 10
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
countdown(time_in_seconds)
for more details, check out this LINK

How to create a timer that resets for quiz games?

I trying to create a timer for my quiz game. It should reset after every right question. But problem with my code is that it keeps increasing speed after every time it resets.
timeCount = 30
def countdown():
global timeCount
while timeCount > 0:
print(timeCount)
sleep(1)
timeCount -= 1
else:
print("Time Out!")
I think this is what you are trying to do:
import time
timeCount = 30
start = time.time()
seconds = 0
def countdown():
global timeCount
global seconds
while seconds < timeCount:
now = time.time()
seconds = now - start
print(timeCount - seconds)
else:
print("Time Out!")
countdown()
This teaches you how to use time.time. You can take away seconds from timeCount to make a timer that goes down from 30 to 0. When the seconds hits 30, you can end the loop and print "Time out". You can truncate the unnecessary floating point values, since i am assuming floating point numbers doesn't look good on a quiz timer and is unnecessary as well.
seconds = int(seconds)
You can use the function time.perf_counter() :
import time
start=time.perf_counter()
time.sleep(1) #you can replace the sleep function with the action you want to monitor
end=time.perf_counter()
print('elapsed time : ',end-start)
In the example above, time.perf_counter() evaluated the time when it is called so it gives you the elapsed time between the two call.
if you want to use your current logic :
Your 'global' statement means that your are going to modify the 'timeCount' variable during the execution of your code. To fix it, you can use a new local variable in your function (called 'local_count' in the below solution), like this you reset the countdown each time you call your function :
import time
timeCount = 30
def countdown():
local_count = timeCount
while local_count > 0:
print(local_count)
time.sleep(1)
local_count -= 1
print("Time Out!")

Python: Run code every n seconds and restart timer on condition

This may be simpler than I think but I'd like to create timer that, upon reaching a limit (say 15 mins), some code is executed.
Meanwhile every second, I'd like to test for a condition. If the condition is met, then the timer is reset and the process begins again, otherwise the countdown continues.
If the condition is met after the countdown has reached the end, some code is executed and the timer starts counting down again.
Does this involve threading or can it be achieved with a simple time.sleep() function?
You could probably accomplish it with threading really elegantly but if you need a quick fix you could try
import time
timer = 15 * 60 # 60 seconds times 15 mins
while timer > 0:
time.sleep(0.985) # don't sleep for a full second or else you'll be off
timer -= 1
if someCondition:
timer = 15 * 60
executeCode() # called when time is zero and while loop is exited
If the whole process is as simple as you say, I would go about it like this (semi-psuedo-code):
def run_every_fifteen_minutes():
pass
def should_reset_timer():
pass
def main():
timer = 0
while True:
time.sleep(1)
timer+=1
if should_reset_timer():
timer = 0
if timer == 15*60:
run_every_fifteen_minutes()
timer = 0
Note that this won't be exactly fifteen minutes in. It might be late by a few seconds. The sleep isn't guaranteed to sleep only 1 second and the rest of the loop will take some time, too. You could add a system time compare in there if you need it to be really accurate.
Thanks for the help everyone, your answers pointed me in the right direction. In the end I came up with:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import subprocess
GPIO.setmode(GPIO.BCM)
PIR_PIN = 4
GPIO.setup(PIR_PIN, GPIO.IN)
timer = 15 * 60 # 60 seconds times 15 mins
subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)
try :
print "Screen Timer (CTRL+C to exit)"
time.sleep(5)
print "Ready..."
while True:
time.sleep(0.985)
# Test PIR_PIN condition
current_state = GPIO.input(PIR_PIN)
if timer > 0:
timer -= 1
if current_state: #is true
# Reset timer
timer = 15 * 60
else:
if current_state: #is true
subprocess.call("sudo /opt/vc/bin/tvservice -p", shell=True)
# Reset timer
timer = 15 * 60
else:
subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)
except KeyboardInterrupt:
print "Quit"
GPIO.cleanup()
To put it in context, I'm using a PIR sensor to detect motion and switch on an hdmi connected monitor on a Raspberry Pi. After 15 mins of no movement I want to switch the monitor off and then if (at a later time) movement is detected, switch it back on again and restart the time.
The description sounds similar to a dead main's switch / watchdog timer. How it is implemented depends on your application: whether there is an event loop, are there blocking functions, do you need a separate process for proper isolation, etc. If no function is blocking in your code:
#!/usr/bin/env python3
import time
from time import time as timer
timeout = 900 # 15 minutes in seconds
countdown = timeout # reset the count
while True:
time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
countdown -= 1
if should_reset_count():
countdown = timeout # reset the count
if countdown <= 0: # timeout happened
countdown = timeout # reset the count
"some code is executed"
The code assumes that the sleep is never interrupted (note: before Python 3.5, the sleep may be interrupted by a signal). The code also assumes no function takes significant (around a second) time. Otherwise, you should use an explicit deadline instead (the same code structure):
deadline = timer() + timeout # reset
while True:
time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
if should_reset_count():
deadline = timer() + timeout # reset
if deadline < timer(): # timeout
deadline = timer() + timeout # reset
"some code is executed"
What is the best way to repeatedly execute a function every x seconds in Python?
How to run a function periodically in python
Maybe you should look into the Linux tool cron to schedule the execution of your script.

Creating a timer in python

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
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box, The dialog box is not the problem. But my minutes variable does not increment in this code.
See Timer Objects from threading.
How about
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()
Should you want pass arguments to the timeout function, you can give them in the timer constructor:
def timeout(foo, bar=None):
print('The arguments were: foo: {}, bar: {}'.format(foo, bar))
t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
You can really simplify this whole program by using 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
I'd use a timedelta object.
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
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
or
minutes = minutes + 1 #instead of mins = minutes + 1
but here's another solution to this problem:
def wait(time_in_seconds):
time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.
All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.
import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()
# 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
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
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)
This work very good to time seconds.
You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
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.
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
I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that
minutes = 0
and then
mins = minutes + 1
it is the same as saying
mins = 0 + 1
I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".
What you have to do first is place your
minutes = 0
declaration outside of your while loop. After that you can delete the
mins = minutes + 1
line because you don't really need another variable in this case, just replace it with
minutes = minutes + 1
That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.
I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.
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

How do you make two functions work side by side in python?

I am very new to python and am taking a course at my school, I was given the homework of making a clock that counts down from 1 or 2 hours and also shows the minutes seconds and hours the whole time. I started to do the code and defined 2 functions, seconds, and minutes. Seconds counts down from 60 seconds and minutes does the same thing except from 1 minute, I tried them seperatly and they worked, then I tried them together and I couldn't get them to work side by side. How can I make them do this, also, should I just be using a variable that counts down? Any help is appreciated.
from time import *
def seconds():
while 1==1:
time_s = 60
while time_s != 0:
print (time_s)
sleep(1)
time_s=time_s-1
os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
def minutes():
while 1==1:
time_m = 60
while time_m!= 0:
print (time_m)
sleep(60)
time_m = time_m-1`
Also, indents might be messed up.
As there are sixty seconds in a minute. You don't need to calculate them separately. Just calculate the total amount of seconds and divide by 60 to show the minutes, and modulo 60 to show the seconds.
Your Desired Complete Program
import threading
import logging
import time
time_m=60
time_s=60
time_h=24
print ('Karthick\'s death Clock Begins')
def seconds():
while 1==1:
global time_s,time_m,time_h
time_s = 60
while time_s != 0:
print (time_h,':',time_m,':',time_s)
time.sleep(1)
time_s=time_s-1
os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
def minutes():
while 1==1:
global time_m
time_m = 60
while time_m!= 0:
time.sleep(60)
time_m = time_m-1
def hours():
while 1==1:
global time_h
time_h = 24
while time_h!= 0:
time.sleep(360)
time_h = time_h-1
m=threading.Thread(name='minutes',target=minutes)
s=threading.Thread(name='seconds',target=seconds)
h=threading.Thread(name='hours',target=hours)
m.start()
s.start()
h.start()
Enjoy Programming :-)!

Categories