I'm trying to make a break timer. I can get the current second value, but I don't know how to reset the seconds and start counting down
I've tried several formulas found here on stack overflow, but have yet to find what I'm looking for
import time
while True:
now = time.localtime(time.time())
print(now[5])
time.sleep(1)
I expect the output to count down from 59 and start over
output: count up from current second
Why don't you use something like:
import time
sec = 0
while True:
print(59 - sec)
time.sleep(1)
sec = (sec + 1) % 60
Here is version with a defined function. It will countdown at defined seconds, taking sleep every seconds.
import time
def countdown(t_sec):
while t_sec:
mins, secs = divmod(t_sec, 60)
timeformat = '{:02d}'.format(secs)
print(timeformat)
time.sleep(1)
t_sec -= 1
countdown(59)
Related
Complete newbie here so bare with me. I've got a number of devices that report status updates to a singular location, and as more sites have been added, drift with time.sleep(x) is becoming more noticeable, and with as many sites connected now it has completely doubles the sleep time between iterations.
import time
...
def client_list():
sites=pandas.read_csv('sites')
return sites['Site']
def logs(site):
time.sleep(x)
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
stamp = time.strftime('%Y-%m-%d,%H:%M:%S')
log = open(f"{site}/log", 'a')
log.write(f",{stamp},{site},hit\n")
log.close()
os.remove(f"{site}/target/hit")
else:
stamp = time.strftime('%Y-%m-%d,%H:%M:%S')
log = open(f"{site}/log", 'a')
log.write(f",{stamp},{site},miss\n")
log.close()
...
if __name__ == '__main__':
while True:
try:
client_list()
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(logs, client_list())
...
I did try adding calculations for drift with this:
from datetime import datetime, timedelta
def logs(site):
first_called=datetime.now()
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=5)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
...
It ends up with a duplicate entries in the log, and the process still drifts.
Is there a better way to schedule the function to run every x seconds and account for the drift in start times?
Create a variable equal to the desired system time at the next interval. Increment that variable by 5 seconds each time through the loop. Calculate the sleep time so that the sleep will end at the desired time. The timings will not be perfect because sleep intervals are not super precise, but errors will not accumulate. Your logs function will look something like this:
def logs(site):
next_time = time.time() + 5.0
while 1:
time.sleep(time.time() - next_time)
next_time += 5.0
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
# do something that takes a while
So I managed to find another route that doesn't drift. The other method still drifted over time. By capturing the current time and seeing if it is divisible by x (5 in the example below) I was able to keep the time from deviating.
def timer(t1,t2)
return True if t1 % t2 == 0 else False
def logs(site):
while 1:
try:
if timer(round(time.time(), 0), 5.0):
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
# do something that takes a while
time.sleep(1) ''' this kept it from running again immediately if the process was shorter than 1 second. '''
...
I have a question on how I am able to set the timer so that every time it exits the loop it sets the time back to 2 seconds. The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately. Thank you very much in advance for any advice.
This is my code:
time = 2
while time > 0:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
winsound.Beep(freq, duration)
I am not sure if you meant that, but for me it seems like you just want to wait 2 seconds before executing the next steps. You can do that like so:
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
Anyways I don't recommend you to use a plain infinite loop, without a break statement. Therefore I recommend you to add one, like down below.
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
if True: # break on a specific statment
break
Edit: As CrazyChucky mentioned in the comments, this approach should work fine in most of the cases, but it can end up being more than two seconds sometimes. Therefore you should work with timedeltas or take a look at scheduler.
To be more accurate as possible use:
import time
timer = 0
step = 2
t0 = time.time()
while True:
timer = time.time() - t0
wait = step - timer
time.sleep(wait)
print(time.time())
winsound.Beep(freq, duration)
t0 = time.time()
This script take in count the execution time of script lines for your computer.
You just have to reinitialize the time at the end of the loop
time = 2
while True:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
if time == 0:
time = 2
break
winsound.Beep(freq, duration)
I'm making a program that runs something for the amount of minutes the user alots (it's an idle game in beta). I put on a timer for one minute and noticed that the program ran over the minute by a couple of seconds-- Not very noticable, but I was wondering if this is because of how long a loop takes to execute? This is my code:
import time
foreverloop = True
automodeOn = False
idleSec = 0
idleMin = 0
pages = 0
pps = 0
while foreverloop:
if automodeOn == False:
msg = input("BTCG Command >> ")
if msg == 'auto':
autotime = input("How long would you like to go idle for? Answer in minutes.")
automodeOn = True
elif msg == 'autoMORE':
pps += .5
else:
pages += pps
print("You have auto-read",pps,"pages.")
idleSec += 1
if idleSec == 60:
idleSec = 0
idleMin += 1
if idleMin == int(autotime):
print("Idle mode turning off.")
automodeOn = False
time.sleep(1)
You could measure the time it takes for a number of lines of code to execute by measuring the start time:
start = time.time()
before any number of lines you'd like to measure the time, then at the end adding:
end = time.time()
the time elapse is then calculated as their subtraction:
elapsed_time = end-start
I suggest that you read about code complexity, the most popular of which is the Big O notation.
edit: as denoted in a comment, timeit is the better option if you're looking to precisely measure the time it takes for a certain line or function to execute, the main difference between the 2 approaches is that timeit is made specifically for this purpose and as part of this takes as a parameter a variable number indicating the number of times the specified code is run before determining how long it takes on average to run.
Instead of making the program wait in adittion to the time it takes to execute, I would use time.time() to get the system's current UNIX time in seconds as a float and only continue if a certain time has passed:
import time
time_begin = time.time()
wait_time = 60 # seconds to wait
while time.time() < time_begin + wait_time:
# do logic
print("Time passed:", time.time() - time_begin)
time.sleep(1) # can be whatever
print(wait_time, "seconds has passed!")
I know this question is not that good but I am kind of stuck here and I've been searching about timers but the answers are just not what I am looking for.
Okay so I have a for loop here and this for loop is trying to do something continuously but I need it to do its task for a minute that I have chosen and let's say 3 minutes , so it would be like
for i in sample_iteration:
#Tasks are being done here
But I need those tasks inside the for loop to keep going for 3 minutes and I have found this timer from geeks for geeks and this is the code
# import the time module
import time
# define the countdown func.
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
print('Fire in the hole!!')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
countdown(int(t))
Now I tried this one right here, now it does the countdown for 3 minutes but it also does the time.sleep(1) for one second and I can't have it paused for every second cause I need to to keep going as possible.
t = 180 #seconds
for i in sample_iteration:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
#Do the task here
I can easily I think make a condition that when t is 0 I could break the loop
Now long ago I had this java program that does the work and involves some nano time with I understand this and the counting is based on nano time cause 100000000 nanoseconds is equal to 1 second right? (correct me if I am wrong) so yeah and here is the code
public class Timer {
public static void main(String[] args){
long lastTime = System.nanoTime();
boolean running = true;
int timer = 0;
long now ;
int i = 0;
while(running)
{
now = System.nanoTime();
timer += (now - lastTime);
lastTime = now;
if(timer >= 1000000000)
{
i++;
timer = 0;
System.out.println(i);
}
}
}
}
I was thinking of doing the same with python but I'm getting lost to be honest and I am just a beginner and tried to get help here in this great community! Also maybe there's an alternative where I do not have to apply based on the java program cause maybe there's a better way and shorter way with python. Thank you! Looking forward for this THANK YOU!
import time
def countdown(t):
start_time = time.time()
while True:
if int(time.time()-start_time) == t:
quit()
try this.
---UPDATE---
Hello I managed to figure it out! Thanks for the answers this is what I've done
i = 0
lastTime = time.time_ns()
timer = 0
for i in sample_iteration:
now = time.time_ns()
timer += (now - lastTime)
lastTime = now
if timer >= 1000000000:
i+=1
timer = 0
print(i)
I used the time.time_ns() to get the nanoseconds cause time.time() is different vs time.time_ns(). time.time() is getting the time in seconds since the epoch and it is not in nano seconds which is what I was looking for
time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method.
The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Source: Geeks for Geeks
Thank you stack overflow community!
I have some code here that prints a line one time every minute but I want to change it so it prints the message for one minute straight then pauses for one minute indefinitely. How do I achieve this?
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
To print the message constantly for a minute, then wait for a minute, then repeat indefinitely, you can use the following:
import time
while True:
s = time.time()
while time.time() < s + 60:
print("Message")
time.sleep(60)
If you want to print the message every second for one minute. You can do something like below:
import time
original_time = time.time()
while time.time() < original_time + 60:
print("This prints every second for one minute")
time.sleep(1)
Is that what you are looking for?
You can track when you start your minute, and then wait 60 seconds. Each 60 seconds you switch the state of is_printing.
import time
is_printing = False
while True:
is_printing = not is_printing
start_time = time.time()
while time.time() - start_time < 60:
if is_printing:
print("Printing this for a minute.")