Creating a timer in python - 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

Related

python threading.Timer(second, func).start()

import threading
import datetime
def showA():
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour,now.minute,now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
second = 5
threading.Timer(second, showA).start()
showA()
This code shows me 'timer_checking.. 11:11:27'
second will add +5 for good.
I want to make showA() operate
first 5 seconds
second 4 seconds
third 3 seconds
fourth 2 seconds
fifth 1 second
second == 0
start again 5 seconds.
please Help me.
timer interval change after per operate, so interval must be an argument.
well, showA create a thread for each operate, thread is costly. showA2 may be better.
import threading
import datetime
# I want to make showA() operate
# first 5 seconds second 4 seconds third 3 seconds fourth 2 seconds fifth 1 second, second == 0 start again 5 seconds.
def loop_interval(old_interval):
if old_interval == 1:
return 5
return old_interval - 1
def showA(interval):
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour, now.minute, now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
threading.Timer(interval, showA, args=(loop_interval(interval),)).start()
def showA2():
threading.Thread(target=_show).start()
def _show():
e = threading.Event()
interval = 5
while 1:
e.wait(interval)
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour, now.minute, now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
interval = loop_interval(interval)
if __name__ == '__main__':
showA(5)
# showA2()
print(1)

How do I receive the updated time every time it is called in this function?

import time
seconds = time.time()
local_time = time.ctime(seconds)
print("Start Time:", local_time)
def bot():
x = 0
while x < 16:
time.sleep(1)
print("Time:", local_time)
x += 1
When I run this code it prints the initial time take before the function every time, I would like it to show the updated time every time local time is printed, can someone point me in the right direction?
Using a variable will not re-evaluate it. You'll need to calculate the time again each loop iteration
import time
def bot():
for x in range(16):
time.sleep(1)
seconds = time.time()
local_time = time.ctime(seconds)
print("Time:", local_time)
bot()

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!")

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

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