While Loop is not working well with the time - python

I have a code with this ↓ part in it, which should do something when the time and day come. It has outer and inner time and day checks (while loops).
Outer for the situation in which code starts processing in time (or day) which is not in the timerange for code processing - it should wait until that time (or day). And it works, but only in situation when I set it like 10 minutes before the timerange (code processing time). When I set it like a night before, it won't works and it stops in print("timerange wait") It shows False even it should be True. Is there a problem because it is not in the same day? Or something else? Please give me some advices.
Here is the simple version of code (without unnecessary parts )
import os
import datetime
from time import sleep
from datetime import date
#setting used variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=18, minute=9, second=0, microsecond=0)
# function for check creating "timerange -start time, end time"
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
# main program for doing something
def main():
while True:
# Time period check - Check if time and weekdays are not out of range
# if not in range will wait till the time
if date.today().weekday():
dayz = True
else:
dayz = False
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True:
print("waiting for function-time")
sleep(10)
continue
if dayz != True:
print("waiting for function-days")
sleep(3600)
continue
while True:
print("do something")
#check if during while loop there wasn't date, time change (out of timerange etc)
if date.today().weekday():
dayz = True
else:
dayz = False
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True:
print("break inner loop-timerange")
break
if dayz != True:
print("break inner loop-dayz")
break
print("do something -main work")
#program starts here
timerange = time_in_range(morning, evening, now)
# check if today is weekday (outer loop)
if date.today().weekday():
dayz = True
else:
dayz = False
# if today is not a weekday wait till weekday (outer loop)
#for situation where the code started not in weekday
while dayz != True:
print("days wait")
sleep(3600)
dayz = date.today().weekday()
if dayz == True:
break
# If it is not processing time, wait until it becomes
# for the situation where code started not in "timerange"
while timerange != True:
print("timerange wait") # ---------HERE IT STOPS---------
# But it works fine, when I set it like one hour before 'timerange' or so...
sleep(10)
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
print(timerange)
if timerange == True:
break
# Do the main function
main()
# Let know when code ends
print("Over of Code")

Related

Timer update inside while loop & if statement?

I'm building my first timer in Python and looking into time module. This is what I want:
Inside while loop, when the if condition "A" is true for the first time, start timer
When 10 seconds has passed, trigger an event
When 30 seconds has passed, clear timer so that it's ready to start again when if condition "A" is true
I feel like I have all the building blocks but still cannot get my head around for starting the 10 second timer. In pseudocode, I want this:
if current_time - the_time_from_first_if_statement_match > 10:
do something
This is what I have now. Any help appreciated!
def main():
start_time = time.time()
time_limit = 10
while True:
current_time = time.time() #keeps updating
matchresult = video_process.match
if matchresult == True:
elapsed_time = current_time - start_time #can be anything like 14 or 100 at this point, I'd just want a 10 sec timer
if elapsed_time > time_limit:
print("do something")
Something along these lines:
while True:
while not condition:
...
start_time = ...
while elapsed_time < 10:
...
do_something
while elapsed_time < 30:
...

Python -While loop doesn't work with Time

I have a code which starts a main function. In this function have a while loop which should starts program when certain time comes. I have set this time in morning (start time), evening(end time) variables. It is in while loop and it works, but only if I start the program the day I want to use it. For example: When I start it Monday evening (20:00) and start time(morning variable) is from 8:00 (next day), it will continue loop
print("Waiting for the right time") <=(doing this)
even if that time the next day comes. But It works when I start it the next day at 6:00 or so...
Can someone explain me, why this happens?
Here is the code
import datetime
from time import sleep
from datetime import date
#variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=16, minute=15, second=0, microsecond=0)
#function for time-setting
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#main function
def main():
while True:
# Time period check
if date.today().weekday() < 5 and date.today().weekday() >= 0:
dayz = True
else:
dayz = False
if dayz != True:
print("Waiting for the day")
sleep(3600)
continue
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True: # HERE IT MAKES THE TROUBLE
print("Waiting for the right time")
sleep(200)
continue
print("do something")
main()
print("end of code")
When you call .replace() to set the morning and evening times, it keeps the current date as part of the datetime object. So if you were to call it a day before, the dates would be set to the previous day's date, and thus .now() will never be in between the previous day's time range.
E.g. if on January 1st you make the calls to set morning and evening, the stored datetimes will be "January 1st 8am" and "January 1st 4pm". The next time when your loop is checking, it asks "Is January 2nd 10am between January 1st 8am and January 1st 4pm" and of course the answer is no, because January 1st was the day before.
You probably want to use the datetime.time class instead of the datetime.datetime class, if you're only wanting to check for time. Alternatively, you could set the date portion of your evening and morning datetimes to the specific date you want to match (but that wouldn't help for repeating weekly).
import datetime
from time import sleep
from datetime import date
#variables
now = datetime.datetime.now()
morning = now.replace(hour=8, minute=0, second=0, microsecond=0)
evening = now.replace(hour=16, minute=15, second=0, microsecond=0)
#function for time-setting
def time_in_range(morning, evening, x):
# Updated code
morning = x.replace(hour=8, minute=0, second=0, microsecond=0)
evening = x.replace(hour=16, minute=15, second=0, microsecond=0)
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
print(timerange)
#main function
def main():
while True:
# Time period check
if date.today().weekday() < 5 and date.today().weekday() >= 0:
dayz = True
else:
dayz = False
if dayz != True:
print("Waiting for the day")
sleep(3600)
continue
now = datetime.datetime.now()
timerange = time_in_range(morning, evening, now)
if timerange != True: # HERE IT MAKES THE TROUBLE
print("Waiting for the right time")
sleep(200)
continue
print("do something")
main()
print("end of code")

Keep referencing current time in Python

I would like to have my program reference the current time in Python.
But my program keeps printing and referencing a timestamp. I am using Python3.5.3.
import time
timenow = time.strftime("%X")
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
My current output is...
21:55:46
Lights On
21:55:46
Lights On
21:55:46
Lights On
This might work as well.
If you are referencing time as date part that can be represented an int. I guess its better to compare numbers in this case rather then strings (as in your example).
import datetime
on = 6
off = 22
while True:
ctime = datetime.datetime.now()
status = 'Lights On' if on < ctime.hour < off else 'Lights Off'
print('{}: {}'.format(ctime.strftime('%X'), status))
I think you just need to move 1 line into the while loop:
import time
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
timenow = time.strftime("%X") #moved this line into the while loop
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
The output should now look like:
Lights On
08:50:22
Lights On
08:50:23
Lights On
08:50:24
In the question, timenow gets set and is never updated. So move that into the while loop flow so it gets created each time. Just as good programing practice you may also want to toss a pause in there so it's just not hammering the CPU in the loop. You could put this at the end of the while loop and it will wait 1 second before looping again:
....
elif timenow >= sleep:
print ("Lights Off")
time.sleep(1)

comparing three variables on if statement

I need some help with get pass on the if statement. I have a problem with if statement as I am trying to get pass when I am trying to compare on the values using three variables.
start_time = '22:35'
current_time = '23:48'
stop_time = '00:00'
if current_time == start_time:
print "the program has started"
elif start_time != current_time < stop_time:
print "program is half way"
elif current_time > stop_time:
print "program has finished"
I can get pass on each if statement with no problem, but my problem is when I have the variable start_time with the value 22:35 which it is not equal to current_time value 23:48. So how I can compare with the values between the start_time and current_time as I want to compare to see if it is less than the value 00:00 from the variable stop_time?
I want to check if the value from the variable stop_time which is less than the current_time and start_time.
Just imagine you are watching the tv program which it start at 22:35 in your current time. You are watching which it is less than before the program finish at 00:00, so you check the time again later before the finish time 00:00, it say it is still half way through. Then you check it later at your current time which it is after than 00:00 so it say the program has finished.
Well on my code, I will always get pass on the elif current_time > stop_time: as i always keep getting the print "program has finished" which I should have print "program is half way" instead.
How can you compare three values between the variables start_time and current_time to see if it is less than and check to see if it is less the value 00:00 from the variable stop_time?
EDIT: Here is what I use them as a string when i am getting the hours and minutes from the date format especially year, month, day, hours, minutes and seconds
start_date = str(stop_date[0]) #get start_date date format from database
stop_date = str(stop_date[1]) #get start_date date format from database
get_current_time = datetime.datetime.now().strftime('%H:%M')
get_start_time = time.strptime(start_date, '%Y%m%d%H%M%S')
start_time = time.strftime('%H:%M', get_start_time)
get_stop_time = time.strptime(stop_date, '%Y%m%d%H%M%S')
stop_time = time.strftime('%H:%M', get_stop_time)
current_time = str(get_current_time)
Using two comparisons and the and logical we could create something like this:
if current_time > start_time and current_time < stop_time:
#do work
But that actual problem is dealing with date and time
current_time = datetime.now() #lets say this is 2016, 2, 12, 17:30
start_time = datetime.datetime(2016,2,12,16,30) # or datetime.strptime(start_time)
end_time = datetime.datetime(2016,2,13,0,0)
if current_time == start_time:
print "the program has started"
elif current_time > start_time and current_time < stop_time:
print "Program is still running"
elif current_time > stop_time:
print "program has finished"

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

Categories