delay a task until certain time

Viewed 40516

What I want to do in a python script is sleep a number of seconds until the required time is reached. IE: if runAt setting is 15:20 and current time is 10:20, how can I work out how many seconds to sleep? I'm not sure how to convert 15:20 to a time and current date then deduct the actual time to get the seconds.

8 Answers

Using timedelta object is the way to go. Below is the example that worked for me and can easily be adjusted to any other time:

import datetime, time
today = datetime.datetime.now()

sleep = (datetime.datetime(today.year, today.month, today.day, 15, 20, 0) - today).seconds
print('Waiting for ' + str(datetime.timedelta(seconds=sleep)))
time.sleep(sleep)

Take into consideration that if 15:20 has already passed, this substraction will still work and will wait till the next occurrence of 15:20, because in such situations timedelta returns a negative number of days. It's 16:15 as I'm running my code:

print(datetime.datetime(today.year, today.month, today.day, 15, 20, 0) - today)
>>>-1 day, 23:05:00.176033

Using both arrow and pause:

maintenance = arrow.now()
EndAt = maintenance.replace(hour = 17, minute = 6, second = 0)
print(maintenance,': Maintenance in progress. Pausing until :',EndAt)
pause.until(EndAt.naive)
Related