delay a task until certain time

后端 未结 8 2041
梦谈多话
梦谈多话 2021-01-11 11:59

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 wor

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 12:20

    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
    

提交回复
热议问题