python repeating countdown timer for discord.Py - python

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

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 -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")

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"

Creating a timer in python

import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box, The dialog box is not the problem. But my minutes variable does not increment in this code.
See Timer Objects from threading.
How about
from threading import Timer
def timeout():
print("Game over")
# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()
# wait for time completion
t.join()
Should you want pass arguments to the timeout function, you can give them in the timer constructor:
def timeout(foo, bar=None):
print('The arguments were: foo: {}, bar: {}'.format(foo, bar))
t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
You can really simplify this whole program by using time.sleep:
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# Loop until we reach 20 minutes running
while mins != 20:
print(">>>>>>>>>>>>>>>>>>>>> {}".format(mins))
# Sleep for a minute
time.sleep(60)
# Increment the minute total
mins += 1
# Bring up the dialog box here
I'd use a timedelta object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
or
minutes = minutes + 1 #instead of mins = minutes + 1
but here's another solution to this problem:
def wait(time_in_seconds):
time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.
All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.
import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()
# this is kind of timer, stop after the input minute run out.
import time
min=int(input('>>'))
while min>0:
print min
time.sleep(60) # every minute
min-=1 # take one minute
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that
minutes = 0
and then
mins = minutes + 1
it is the same as saying
mins = 0 + 1
I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".
What you have to do first is place your
minutes = 0
declaration outside of your while loop. After that you can delete the
mins = minutes + 1
line because you don't really need another variable in this case, just replace it with
minutes = minutes + 1
That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.
I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.
from datetime import datetime
now=datetime.now()
Sec=-1
sec=now.strftime("%S")
SEC=0
while True:
SEC=int(SEC)
sec=int(sec)
now=datetime.now()
sec=now.strftime("%S")
if SEC<sec:
Sec+=1
SEC=sec
print(Sec) #the timer is Sec

Categories