Matt Matt - 1 month ago 11
Python Question

Python Sleep Until a Certain Time

I have a Python script and I want too run it at 3 am. Would like to simply put something like this at the top of it.

while not 3am:

That way it keeps sleeping for 10 seconds until it's 3am. At 3am, it executes the rest of the code below this and then exits the script. Is there a simple way to do that?

Answer Source

Solution with a sleep-wait loop:

import datetime
import time

target_time = datetime.datetime(2017, 3, 7, 3)  # 3 am on 3 July 2017
while < target_time:
print('It is 3am, now running the rest of the code')

If instead of sleeping, you want to do other work, consider using threading.Timer or the sched module.