Welcome, guest | Sign In | My Account | Store | Cart

Get tomorrow morning time, make delta from now and wait x seconds.

Python, 7 lines
1
2
3
4
5
6
7
def waitToTomorrow():
    """Wait to tommorow 00:00 am"""

    tomorrow = datetime.datetime.replace(datetime.datetime.now() + datetime.timedelta(days=1), 
                         hour=0, minute=0, second=0)
    delta = tomorrow - datetime.datetime.now()
    time.sleep(delta.seconds)

5 comments

Denis Barmenkov 14 years ago  # | flag

I've remembered a joke about some xxx programming style:

Q:

how to calculate tomorrow date?

A:

def get_tomorrow_date():
    time.sleep(24*60*60 sec)
    return datetime.datetime.now()
Mateyuzo 14 years ago  # | flag

heh. then kill -9?

how about a Timer with a timeout. or

how about something like.. (say its a threading.Thread subclass):

while self._continue_execution(): try: self._condition.acquire() self._condition.wait(self._get_seconds_till_tomorrow()) # you should check again if self._continue_execution(): . . .

Mateyuzo 14 years ago  # | flag

Sorry.. didn't indent, bleg.

so some close() method could set a stop flag and notify _condition

while self._continue_execution(): 
    try: 
        self._condition.acquire() 
        self._condition.wait(self._get_seconds_till_tomorrow())
        # you should check again 
        if self._continue_execution(): 
        . . .
Wolfgang Beneicke 13 years, 12 months ago  # | flag

Your code will be off by the current number of minutes. It probably should have been:

import datetime as dt

def waitToTomorrow():
    '''Wait to tomorrow 00:00 am.'''
    tomorrow = dt.datetime.replace(dt.datetime.now() + dt.timedelta(days=1),
                   hour=0,minute=0,second=0)
    delta = tomorrow - dt.datetime.now()
    time.sleep(delta.seconds)

i.e. you left out the minutes.

For simplicity, I suggest using the time module only:

import time

def waitToNextMidnight():
    '''Wait to tomorrow 00:00 am.'''
    t = time.localtime()
    t = time.mktime(t[:3] + (0,0,0) + t[6:])
    time.sleep(t + 24*3600 - time.time())
vojta rylko (author) 13 years, 11 months ago  # | flag

Thanks Wolfgang, you are right. I've repaired it.

Created by vojta rylko on Wed, 7 Apr 2010 (MIT)
Python recipes (4591)
vojta rylko's recipes (1)

Required Modules

Other Information and Tasks