I don't know how to use the while loop in Python so that it will notify me if reaches a certain time.
from datetime import datetime
import time
import os
now = datetime.now()
end = 1
while x == 1:
global end
if now.minute == *TIME*:
end = 0
print ("Notification")
My interpretation of what you asked:
import datetime, time
def delay(end_time):
while datetime.datetime.now() < end_time:
time.sleep(.1) # wait .1 seconds before continuing
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds=60) # add 60 seconds
delay(end_time)
print('done')
I was a little confused by what you were doing. Something to notice is the use of less than, instead of equals in the while loop. If you use equals it will only exit if the code is evaluated at the exact time you specified (this is very unlikely to ever happen, so you will be stuck in the loop forever). But with less than you can exit the first time it notices you have waited long enough. You could replace all of this with just time.sleep(60).
Related
I have been looking around, and I am sure the answer is right in front of me, but I am using the datetime for the first time and had a question. So short version is I have a script that reads a csv and looks for start and stop times for yard moves. I need to take those times and subtract them to see how long it took. I am not sure if using strptime is the right way to go about it or not. I am also confused as to why I can not subtract the stop_time and start_time from each other even though they are datetime.datetime types.
import csv
from datetime import datetime, date
start_time = '0'
stop_time ='0'
trailer = '0'
t_time = open('move_times.csv')
t_time_reader = csv.reader(t_time, delimiter=',')
for i in t_time_reader:
if i[2] == 'HOSTLER_COMPLETE':
stop_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
trailer = i[11]
elif i[2] == 'HOSTLER_START' and i[11] == trailer:
start_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
print(stop_time - start_time)
The problem is that on the first iteration at least one of start_time and stop_time will necessarily be the string '0'.
Consider the first iteration of the loop. start_time == stop_time == '0', because you set them to this string before the loop.
Then, this if statement is executed:
if i[2] == 'HOSTLER_COMPLETE':
stop_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
trailer = i[11]
elif i[2] == 'HOSTLER_START' and i[11] == trailer:
start_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
Here are the possible scenarios:
(i[2] == 'HOSTLER_COMPLETE') is True, so the first branch is taken. Then:
stop_time becomes a valid date
start_time remains equal to the string '0'
OR (i[2] == 'HOSTLER_START' and i[11] == trailer) is True, so the second branch is taken. Then:
start_time becomes a valid date
stop_time remains equal to the string '0'
OR neither branch is taken, since there's no explicit else branch. Then:
start_time remains equal to the string '0'
stop_time remains equal to the string '0'
Thus, after the if statement, at least one of start_time and stop_time will necessarily equal '0'.
Subtracting anything from a string is an error (as is subtracting a string from anything), so print(stop_time - start_time) fails. Thus, the first iteration of the loop fails, dragging along the entire program.
I am trying to code a function that recognizes when X amount of seconds has passed without pausing the program, so without using time.sleep. How would I be able to do that by using the unix timestamp? So for the code below it would print 5 seconds has passed for every 5 seconds that passes.
import time
X = 5
TIME = time.time()
Check this will help you avoid using time.sleep() and your code will be iterating till the time reaches next X seconds
import time
startTime = time.time()
X = 5
timeDif = 0
while timeDif < X:
currentTime = time.time()
timeDif = currentTime - startTime
Hello I'm trying to make a countdown timer with exactly milliseconds and print it to terminal.
input : a float value like (9.200)
output : countdown time for 9 seconds 200 milliseconds
like below site tool
https://www.online-stopwatch.com/countdown-timer/
even i could try to print time in milliseconds format but the time is not exactly. Maybe it's a not good question but Is there any way to do it?. Thank you guys so much.
I tried to search about this case but can't match any
Below code is what i got from internet but time is not correct and i need a countdown timer a above site had. Thanks
from __future__ import print_function, division
import time , datetime
counter, timestr = 0, ''
print(time.asctime())
t0 = time.time()
try:
while True:
sectime, ff = divmod(counter,1000)
mintime, ss = divmod(sectime,60)
hh, mm = divmod(mintime, 60)
print(''.join('\b' for c in timestr), end='')
timestr='%02i:%02i:%02i.%2s' % (hh, mm, ss, ff)
print(timestr, end='')
time.sleep(.1)
counter += 1
except KeyboardInterrupt:
t0 = time.time() - t0
print('\nCounter seconds: %.1f, time.time seconds: %.1f'
% (counter/10.0, t0 ))
You haven't mentioned what exactly didn't work for you, but I'll attempt to give a general answer anyway. You could try something like this -
# Saved as timer.py
import sys, time
## Create the variable _TIME from sys.argv or wherever, make sure it is a valid float, > 0, etc etc
## Depends on how you expect input
_TIME = 5 # Just for example, remove this
while _TIME > 0:
m, s = divmod(_TIME, 60)
h, m = divmod(m, 60)
print(f"\r{int(h)}".rjust(3,'0'), f"{int(m)}".rjust(2,'0'),
f"{s:.3f}".rjust(5,'0'), sep=':', end='')
_TIME -= 0.001
time.sleep(0.001)
else:
print("\r Completed ! ")
Then use $ python3 timer.py 5 or something like that in your terminal.
Notes :
This may not be accurate, especially if your print statement is slow in the the terminal. See What is the best way to repeatedly execute a function every x seconds? for several better alternatives since accuracy may be important here.
In some terminals/GUIs, \r may not actually move the cursor back to the start of the line as expected. You might not be able to really do anything about this, that's a problem with the terminal app.
Edit:
Right after I posted this, I saw that you'd updated your question. The code vou've shared definitely has problems - its a lot for me to completely explain here. The most obvious is time.sleep(0.1) waits 100ms, not 1, so your timer won't ever update that often. Try reading other sources on how to accomplish what you want.
I have this piece of code, which I had written a few weeks ago. Initially I wrote it for Python 2.7 and it works very well, but I decided some time ago to just abandon it, and move to Python 3.7. Can anyone explain me why this while loop is infnite and doesn't want to fullfill those conditions?
In Python 2.7 this code allows me to browse between my files of data, and those amateurs tricks in my code allows me to handle obstackles such as changing hour after 60 minutes or date after 24 hours. Still have no idea how to convert it to Python 3.
# Input variables
h = "Arctic"
u = 'Denver'
p = 'Patagonia'
Station = input('Enter a station name (Arctic = h, Denver = u, Patagonia = p): ')
Date = input('Enter date time (yyyymmdd): ')
Date_end = input('Enter end date time (yyyymmdd): ')
Start_time_hours = int(input('Enter start time (hh): '))
Start_time_minutes = int(input('Enter start time (mm): '))
End_time_hours = int(input('Enter end time (hh): '))
End_time_minutes = int(input('Enter end time (mm): '))
Save_Print_SavPrin = input('Press s = Save, p = Plot: ')
while Start_time_hours == Start_time_hours and Start_time_minutes == Start_time_minutes and Date == Date:
Start_time_hours += (Start_time_minutes / 60)
Start_time_minutes %= 60
str(Start_time_minutes)
str(Start_time_hours)
str(End_time_minutes)
str(End_time_hours)
Start_time_hours_format = '{:02}'.format(Start_time_hours)
Start_time_minutes_format = '{:02}'.format(Start_time_minutes)
End_time_hours_format = '{:02}'.format(End_time_hours)
End_time_minutes_format = '{:02}'.format(End_time_minutes)
int(Start_time_minutes)
Start_time_minutes += 5
if Save_Print_SavPrin == "p":
print("Showing figures...")
print ("Succesful!")
if Start_time_hours_format == End_time_hours_format and Start_time_minutes_format == End_time_minutes_format and Date == Date_end:
print (Start_time_hours_format, Start_time_minutes_format, End_time_hours_format, End_time_minutes_format)
break
First, your loop condition is an infinite loop, because you're comparing variables to ... themselves. So you can replace by while True: (valable for both python versions)
Now the problematic code is this:
Start_time_hours += (Start_time_minutes / 60)
in python 3, / 60 performs floating point division, even between integer operands. The result is that now Start_time_hours is a float, and can never be equal to End_time_hours, which is an integer (the if Start_time_hours_format == End_time_hours_format test always fails, specially because you're converting both to string).
The fix (works for both versions) is to force integer division:
Start_time_hours += (Start_time_minutes // 60)
Aside, doing str(something) alone on a line isn't going to turn that something into a string unless you assign it back to something. You can remove all those statements, as they're useless anyway.
So I'm making a Quiz for a school project and I want to start a timer at the start of the Quiz which will be stopped at the end and printed the time took for the player to complete the Quiz, I put the Timer that I created at the start but my program gets stuck at the 'While loop' and doesn't continue with the program.
Heres the beginning of my code:
import time
score = 0
lives = 3
o = 1
timer = 0
while o == 1:
time.sleep(1)
timer += 1
I add 1 to 'o' just before the Quiz ends so I can print out the time taken but I can get past the start
Your While loop isnt comparing the value of 'o'. Use == not = and check.