How to create a Python timer to count down? - python

My code:
def timer():
while True:
try:
when_to_stop = 90
except KeyboardInterrupt:
break
except:
print("error, please star game again")
while when_to_stop > 0:
m, s = divmod(when_to_stop, 60)
h, m = divmod(m, 60)
time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" +
str(s).zfill(2) # got cut off, belongs to the line before this
print("time:", time_left + "\r", end="")
if time_left == 0:
print("TIME IS UP!")
time.sleep(1)
when_to_stop -= 1
This works perfectly fine, except that time.sleep means my whole program sleeps, so anything after that while stop for 90 seconds. Any way to fix that?(or make a new timer without time.sleep?)

I think that, alternatively, you could keep track of when the timer starts, and check the time by seeing if the time that's passed is longer than the timer is supposed to last. I'm not sure how much you know about classes and objects in Python, but here is the solution that came to mind:
import datetime
class Timer:
def __init__(self,**kwargs):
self.start = datetime.datetime.now()
self.length = datetime.timedelta(**kwargs)
self.end = self.start+self.length
def isDone(self):
return (self.end-datetime.datetime.now()).total_seconds()<=0
def timeLeft(self):
return self.end-datetime.datetime.now()
def timeElapsed(self):
return datetime.datetime.now()-self.start
Even if you don't quite understand the class itself, if you put it in your code it should work like a charm:
#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)
while(not t.isDone()):
#Do other game stuff here....
time_left = t.timeLeft()
print(f"time: {time_left}")
#And here....
print("Done now")

Related

should i use for loop or while loop to make a break timer in python?

I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()

Is there anyway to add a Defusal Sequence whilst a countdown is happening

I am attempting to program a defusable bomb for a csgo prop and was trying to make it as close as i can to the original thing. I have got everything working smoothly. An entry code and a Timer. The only thing I need to do is add a defusable section to it. Whilst the Bombs timer is running I would need to be able to cancel that action with an Input Code. Where, and what would I put?
I have tried doing a
defuse = input("Defusal Code")
if defuse == "7355608":
break
import time
while True:
uin = input("")
try:
when_to_stop = abs(int(uin))
except KeyboardInterrupt:
break
except:
print("NAN!")
while when_to_stop > 0:
s, ms = divmod(when_to_stop, 100)
m, s = divmod(s, 60)
time_left = str(m).zfill(2) + ":" + str(s).zfill(2) + ":" + str(ms).zfill(2)
print(time_left, end="\r")
time.sleep(0.01)
when_to_stop -=1
print()
print("BOMB DETONATED")

Stop the program execution after some time interval

I have the following code and I want to stop the program if the condition is not true for a certain period of time. Suppose the condition (sum>99999) is false for a period of 10 seconds, then this program stops and gives present sum values. I am on Windows. Any idea how to do it in Windows.
for j in i:
sum=sum+A[j]
if(sum>99999):
print("Current sum is",sum)
This should accomplish what you're describing.
import time
import sys
start_time = time.time()
for j in i:
sum = sum + A[j]
if sum > 99999:
print("Current sum is ", sum)
start_time = time.time() # reset timer if the condition becomes true
elif time.time() - start_time >= 10:
print("Current sum is ", sum)
sys.exit()
Try this:
import time
import sys
start = time.time()
for j in i:
sum += A[j]
if sum > 99999:
print(sum)
elif time.time() - start > 10:
print(sum)
break # if you just want to exit the loop or sys.exit() if you want to exit the program
Sometimes an iteration is heavy enough to render technique proposed by other answers pretty useless. If you don't have access to break execution upon condition, this or that recipes would be helpful.
I will copy the simpler one (and the one I prefer in my code):
import threading
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result
import sys
import time
start_time = time.time()
time_limit = 2
if (comdition):
if((time.time() - start_time) > time_limit):
sys.exit()
else:
#more stuff here

Stopping Stopwatches

I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():

clock countdown calculation in python

I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.
The problem is here:
while h==0:
while m==0:
while s>0:
If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
just convert it all to seconds and convert it back when you print ...
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"

Categories