now_time is not getting updated while code is looping - python

i'm trying to do a loop, that keeps checking if time is between 2 times.. so it turns my lights on. but while its looping the current time does not get updated. im trying to create a aquarium controller, that turns 3 sets of lights on a different times.
thanks for your help :)
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the interval"
print now_time
time.sleep( 9 )
else:
print "no"

You'll need to keep updating now_time in your loop:
while True:
if time (9,30) <= now_time <= time (16,15):
print "yes, within the interval"
now_time = datetime.now().time()
print now_time
time.sleep( 9 )
else:
print "no"
You can replace the conditions with a chained comparison, which is more readable.
You can also set the comparison as the condition on the while, in which case the loop only runs in the specified duration and needs to be restarted for the cycle of the duration:
while time (9,30) <= now_time <= time (16,15):
print "yes, within the interval"
now_time = datetime.now().time()
print now_time
time.sleep( 9 )

If you want to do a loop, you should use one, like while.
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
print time(19,30)
print now_time
while True:
if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the interval"
print now_time
time.sleep( 9 )
else: print "no"
If you want to make an aquarium controller you should check the lights state in every iteration:
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
print time(19,30)
print now_time
while True:
if now_time >= time (9,30) and now_time <= time (16,15):
if isLightOff: lightOn
time.sleep( 9 )
else: if isLightOn: lightOff

Related

Clock script not working, when the seconds reach to 10, 30 or 60, the specific text("half minute passed.. etc") doesnt print. The rest works perfectly

import datetime
import time
now = datetime.datetime.now()
while True:
now = datetime.datetime.now()
seconds = (now.strftime("%S"))
print(seconds)
if (seconds) == 10:
print("ten seconds has passed!")
if seconds == 30:
print("half minute has passed!")
if seconds == 00:
print("one minute has passed!")
time.sleep(1)
seconds is a string, you need to convert it to int before you compare it to int
seconds = int(now.strftime("%S"))
Although this is not needed, you can just use now.seconds
When you use now.strftime("%S"), it returns the seconds in string format, thus envelope it in an int() bracket to convert it into an integer so that it compares integers in your if statement. Move your time.sleep(1) up so that it doesnt print out multiples per second, only 1. The code below should work for you.
import datetime
import time
now = datetime.datetime.now()
while True:
now = datetime.datetime.now()
seconds = int(now.strftime("%S"))
time.sleep(1)
print(seconds)
if (seconds) == 10:
print("ten seconds has passed!")
if seconds == 30:
print("half minute has passed!")
if seconds == 00:
print("one minute has passed!")
The indentation is wrong, the if statements and sleep will never be executed.
Also, use now.second instead of now.strftime("%S").
import datetime
import time
while True:
now = datetime.datetime.now()
seconds = now.second
print(seconds)
if seconds == 10:
print("ten seconds has passed!")
if seconds == 30:
print("half minute has passed!")
if seconds == 00:
print("one minute has passed!")
time.sleep(1)
````

python repeating countdown timer for discord.Py

I'm trying to make a python bot and as one off the commands i want to dsiplay how long it will be until the server restarts (11pm est) every day.
this is the code i wrote but it gives some weird outputs sometimes, when it's midnight it returns 40 hours until restart.
Can anyone help me out here?
#client.command()
async def gettime(self):
now = datetime.now()
# 11 est == 17 gmt+1
reset = datetime.strptime('16:00', '%H:%M')
if now == reset:
await self.send('the restart is happening now')
elif now < reset:
untilrestarthour = reset.hour - now.hour
untilrestartminute = 60 - now.minute
await self.send(f'the restart is happening in {untilrestarthour} hours and {untilrestartminute}''s ')
elif now > reset:
untilrestarthour = 24 - (now.hour - reset.hour)
untilrestartminute = 60 - now.minute
await self.send(f'the restart is happening in {untilrestarthour} hours and {untilrestartminute} minute''s ')
else:
await self.send("error")
In current version you substract from 24h and from 60minutes so finally you substract from 24h+60minutes which gives 25h. You would have to do something like
untilrestarthour = reset.hour - now.hour
if now.minute > 0:
untilrestarthour -= 1
untilrestartminute = 60 - now.minute
else:
untilrestartminute = 0
But maybe better you should use correct date instead of 1900-01-01 and then you can use now - reset or reset - now to calculate hours and minutes correctly.
from datetime import datetime, timedelta
now = datetime.now()
reset = now.replace(hour=16, minute=0)
#reset += timedelta(days=1) # next day
print(' now:', now)
print('reset:', reset)
print('reset-now:', reset-now)
print('now-reset:', now-reset)
if now == reset:
print('the restart is happening now')
elif now < reset:
print('reset in the future:', reset-now)
elif now > reset:
print('reset in the past:', now-reset)
else:
print("error")
Result
now: 2020-05-20 17:49:04.029570
reset: 2020-05-20 16:00:04.029570
reset-now: -1 day, 22:11:00
now-reset: 1:49:00
reset in the past: 1:49:00
The only problem is that now - reset (reset - now) creates object datetime.timedelta which can generate string 1:49:00 but it can't gives separatelly hours 1 and minutes 49. It gives only total seconds and you have to manually conver seconds to hours and minutes
print('reset:', reset)
print(' now:', now)
diff = (reset-now)
print('diff:', diff)
seconds = diff.seconds
print('seconds:', seconds)
hours = seconds//3600
seconds = seconds % 3600
minutes = seconds // 60
seconds = seconds % 60
print('hours:', hours, '| minutes:', minutes, '| seconds:', seconds)
Result:
reset: 2020-05-21 16:00:37.395018
now: 2020-05-20 18:00:37.395018
diff: 22:00:00
seconds: 79200
hours: 22 | minutes: 0 | seconds: 0

Python- How to prevent programs from opening unless the correct password is input

I've got a program that prevents distractions, IE: a video game, from opening between the hours of 12:00am and 8:00pm. It works great, however, I want to add some code to ensure that I cannot exit the python program, or process manually. This way, I can get a friend to choose a password which must be typed in order to exit the python script and allow the game to run.
I've tried getting the password input & requiring the password to exit the script, but the problem is I am still able to manually close the .pyw process with Ctrl+Alt+Delete.
import subprocess
from time import sleep
from datetime import datetime
from datetime import time
i = 0
#Prevent Any Program before 8pm and after 11pm
#current date & time
now = datetime.now()
now_time = now.time()
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
noProgram = 'Phoenix.exe'
noPrevent = "preventProgram.pyw"
while True:
print(time(0,00))
#If the time is between 12am and 8pm
if now_time >= time(0,00) and now_time <= time(20,00):
print("okay okay okay")
subprocess.call('taskkill /F /IM '+ noProgram, startupinfo=si)
sleep(1) # delay 1 seconds
## print("It's between 12:00am & 7:59pm. Work Hours")
if now_time >= time(20,00) and now_time <= time(23,59):
print("Goodbye")
exit()
## print("it's after 8pm. Game On!")
i += 1
i = 0

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"

Python 2.7 .datetime.datetimenow() and datetime.timedelta()

I have this following code and am stuck in the while loop
I know there is a problem with the while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)): line.
Can anyone help please ?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)
You are asking if the current time is smaller than the current time plus a delta. Of course that's going to be true each and every time, the future is always further away into the future.
Record a starting time once:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
If wait_time doesn't vary in the loop, store the end time (current time plus delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
It may be easier to just use time.time() here:
end = time.time() + 60 * wait_time
while time.time() < end:
You use datetime.datetime.now() in your while loop, what means each iteration you check if the time now is lower then the time now + delta.
That logically wrong, because it will be True forever as the time now will be always lower than the time now plus delta.
You should change it to this:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"

Categories