Simple Stopwatch in python using time.sleep - python

Im trying to create a simple stopwatch using counter logic and sleep function in python. It seems to increment fine and be pretty accurate with the one issue of my if statement.
self.sec = 0
self.min = 0
time.sleep(1)
self.sec = self.sec + 1
if (self.sec == 59):
self.sec = 0
self.min = self.min + 1
I'd like minutes to increment whenever seconds reach 59 as shown. Only problem is for a quick second these two things happen at the same time and reads the wrong time. For example, after 59 seconds it reads 1:59 and then reverts back to 1.1 and continues as normal.

First thing: Weird, that your minute would only have 59 seconds instead of 60. Your example would result in the exact behavior described in your problem. Try changing to if (self.sec == 60): ... and check the results.

Related

Trying to sleep milliseconds time.sleep(0.001) not working as expected, alternatives?

I'm trying to run a function approximately 200 times a second (give or take +- 50). When using time.sleep(0.005), I find that it sleeps for much longer. I understand that time.sleep is not accurate, but my use case doesn't need much accuracy either.
I searched this problem up and it seems to be an issue with Windows 10 & 11 in particular: https://bugs.python.org/issue44681
They don't seem to be keen on fixing this issue, so I was wondering what alternatives are there for sleeping for around a millisecond?
I tested this code:
last_time = time.time()
counter = 0
while True:
now = time.time()
if now - last_time >= 1:
print(counter)
last_time = now
counter = 0
counter += 1
Which gave me around 64 to 65 on my computer and around 70 on my laptop.

Can't make the timer decrease more then once

I am trying to create a timer, which right now looks like this:
#Timer 60 sec.
import time
sec = 60
def updateTimer():
trecker.config(text = sec-1)
trecker.after(1000, updateTimer)
trecker = Label(gui, text = sec)
trecker.place(x=500, y=200)
trecker.after(1000, updateTimer)
And the reason I write here is that it displays 60, changes to 59 and then stops. I tried to loop it with for in range, but it doesn't help. My idea right now, is that it calls for updateTimer
function in the inside of its execution restarting itself. But it, for some reason does nothing.
sec-1 is just always 59 because 60-1=59. Instead write:
def updateTimer():
sec -= 1
trecker.config(text = sec)
trecker.after(1000, updateTimer)

Problems when adding to values in a list.[python 2.7.10]

I can't seem to add to the hour. I tried making a clock with a list. A fastforward clock.
Thanks for any help! The problem will be in the first 'if' statement.
import random
import time
ctime = [10, 00] #current_time
#s = random.uniform(.3,1)
s = float(.01)
while True:
if ctime[1] == 59:
time.sleep(s)
ctime.remove(ctime[1])
ctime.insert(00,1)
nhour = int(ctime[0]+1) #next_hour
ctime.insert(nhour, 0)
elif ctime[0] == 23 and ctime[1] == 59:
ctime.remove(ctime[0 and 1])
ctime.insert(00)
ctime.insert(00)
else:
ctime[1]+=1
time.sleep(s)
print(ctime)
Update:
Forgot to show you the output, sorry. It continues as normal, the minutes going from 0-59 and then back to 0, however the hour changes to 02 and stays as 02 even after the minutes have gone by.
I think you've got your argument order for list.insert() confused.
https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
list.insert(i, x) Insert an item at a given position. The first
argument is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
x) is equivalent to a.append(x).
edit: Sorry, forgot to do the actual correction.
Try ctime.insert(1,0) instead.
And also ctime.insert(0, nhour)
You're using the wrong kind of data structure. Lists are for moving a bunch of similar items around so that each can be processed individually. It's a collection. That's not what you're doing. You're trying to take a group of things, and treat them as a single unit, which has known interactions.
What you need is a class. Python already contains many date/time classes, but we can go ahead and implement your use case like this, just for illustration.
class Ticker(object):
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
def tick(self):
self.minute = (self.minute + 1) % 60
self.hour = (self.hour + 1) % 24 if self.minute == 0 else self.hour
And now your loop is much simpler
ticker = Ticker()
while True:
print("%d:%d" % (ticker.hour, ticker.minute))
time.sleep(s)
ticker.tick()

recurring notification statement after checking a condition in python

I am working on a small proof of concept and using python to illustrate the idea. The idea is the program will run in a loop and will check for input. Now if the input falls under a threshold then it sends a notification. But I am trying to restrict the notification at an interval of 4 sec. And thats where I am loosing either with the logic or with some syntax. Either way It is doing some unexpected things
1: keep on entering 0 and it will display the below threshold message until it reaches a 4 sec mark and then it just prints out the message 4 times in a single line. I want them to show after every 4 seconds. The idea is (A)the input might change in that 4 sec and the notification switches. (B)I want the notification to play out as a reminder with a recurrence of 4 sec every time the script hits the condition if weightIn < 0.5..if it is true then the notification goes out after 4 sec from the first time it was sent
Sorry if I tried over explaining it. I am pretty new to python
import threading
def main():
while True:
weightIn = float(input("Get value: "))
threshold = .5
def operation():
if weightIn < 0.5:
#send notification at an interval of 4 sec
threading.Timer(4.0, operation).start()
print("Below weight threshhold...send notification")
else:
print("You are good")
if threshold is not None:
operation()
main()
First avoid declaring functions in a loop. Then ask yourself, if an object would not be appropriate, because it properly encloses state attributes.
But for the algorithmic part, it is simple (if I have correctly understood the problem ...). Store the timestamp of last notification and send a new one if more the 4 seconds have elapsed. In pseudo-code :
last_notification_time = 0
threshold = 0.5
loop:
weighIn = get_new_value()
if weightIn < threshold:
time = get_time_in_seconds()
if (time > last_notification_time + 4):
last_notification_time = time
send_notification()
# actual processing
In Python, it could look like :
#import time
def main():
last_notification_time = 0
threshold = 0.5
while True:
weighIn = float(input("Get value: "))
if weightIn < threshold:
cur_time = time.time()
if (cur_time > last_notification_time + 4):
last_notification_time = time
print("Below weight threshhold...send notification")
# actual processing
main()

Having a certain piece of code run for a specified amount of time

I'm working on a galactica type of game using pygame and livewires. However, in this game, instead of enemy's, there are balloons that you fire at. Every 25 mouse clicks, I have the balloons move down a row using the dy property set to a value of 1. If a balloon reaches the bottom, the game is over. However, I'm having some trouble figuring out how to get this to run only for, say, 1 second, or 2 seconds. Because I don't have a way to "time" the results, the dy value just indefinitely gets set to 1. Therefore, after the first 25 clicks, the row just keeps moving down. This is ok, but like I said, it's not my intended result.
Here is the code I have so far for this action:
if games.mouse.is_pressed(0):
new_missile = missile(self.left + 6, self.top)
games.screen.add(new_missile)
MISSILE_WAIT = 0 #25
CLICKS += 1
if CLICKS == 25:
SPEED = 1
CLICKS = 0
CLICKS, and MISSILE_WAIT are global variables that are created and set to an initial value of 0 before this block of code. What I'm trying to figure out is the algorithim to put underneath the if CLICKS statement. I've looked through the python documentation on the time module, but just can't seem to find anything that would suit this purpose. Also, I don't think using a while loop would work here, because the computer checks those results instantly, while I need an actual timer.
I'm not sure if I got your question but what I can suggest is that:
class Foo():
def __init__(self):
self.start_time = time.time()
self.time_delay = 25 # seconds
def my_balloon_func(self):
if(time.time() - self.start_time) > self.time_delay:
self.start_time = time.time()
else:
# do something

Categories

Resources