Search code examples
pythonsleeptimedelta

How to sleep until a specific time YYYY-MM-DD HH:MM:SS?


I have been thinking to do a sleep function where it sleeps until a certain date is called. My idea was based of date such as : 2019-01-20 12:00:00.

I haven't really figured out how to start to solve this problem. My idea was something similar such as

if there is a date given:
   time.sleep(until the date and time)

So the question is how can I possibly be able to sleep until a certain time given in a value of 2019-01-20 12:00:00?


Solution

  • Easy, calculate how long it is, and sleep the time.

    You can calculate how long it takes until your wakeup time is reached and sleep for the delta time.

    Python can calculate with time intervals. If you subtract one timestamp from another, then you get a datetime.timedelta:

    import datetime
    import time
    
    target = datetime.datetime(2019,1,20,12,0,0)
    
    now = datetime.datetime.now()
    delta = target - now
    if delta > datetime.timedelta(0):
        print('will sleep: %s' % delta)
        time.sleep(delta.total_seconds())
        print('just woke up')
    

    of course, you can put that in a function:

    import datetime
    import time
    
    target = datetime.datetime(2019,1,20,12,0,0)
    
    
    def sleep_until(target):
        now = datetime.datetime.now()
        delta = target - now
    
        if delta > datetime.timedelta(0):
            time.sleep(delta.total_seconds())
            return True
    
    
    sleep_until(target)
    

    You can check the return value: only if it slept, it returns True.

    BTW: it's OK, to use a date in the past as target. This will generate a negative number of seconds. Sleeping a negative value will just not sleep.

    if your time is a string, use this:

    target = datetime.datetime.strptime('20.1.2019 20:00:00', '%d.%m.%Y %H:%M:%s')
    

    or

    target = datetime.datetime.strptime('2019-1-20 20:00:00', '%Y-%m-%d %H:%M:%s')