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.
Think you can also use the following code:
from datetime import datetime, time
from time import sleep
def act(x):
return x+10
def wait_start(runTime, action):
startTime = time(*(map(int, runTime.split(':'))))
while startTime > datetime.today().time(): # you can add here any additional variable to break loop if necessary
sleep(1)# you can change 1 sec interval to any other
return action
wait_start('15:20', lambda: act(100))
If you subtract one datetime object from another you get a timedelta object, which has a seconds property, so you can do:
t1 = datetime.datetime.now()
# other stuff here
t2 = datetime.datetime.now()
delta = t2 - t1
if delta.seconds > WAIT:
# do stuff
else:
# sleep for a bit
As an aside, you might want to use cron for tasks that are supposed to run at specific times.
You could instead use the pause
package ( https://pypi.python.org/pypi/pause ). Taking an example from their documentation -
import pause, datetime
dt = datetime.datetime(2013, 6, 2, 14, 36, 34, 383752)
pause.until(dt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With