Python get datetime of next occurring time

Viewed 339

I am trying to find the NEXT datetime where a specific time occurs.

For example:

now = datetime.datetime.now() # April 5th, 1 PM
desired_time = '14:00:00' # 2 PM
next_datetime_occurance = get_next_datetime(now, desired_time) # Returns April 5th, 2PM

now = datetime.datetime.now() # April 5th, 3 PM
desired_time = '14:00:00' # 2 PM
next_datetime_occurance = get_next_datetime(now, desired_time) # Returns April 6th, 2PM

How would I do this in a clean manner? (Assume everything is in UTC)

1 Answers

You can use datetime.replace() with some datetime arithmetic:

import datetime as dt

def next_datetime(current: dt.datetime, hour: int, **kwargs) -> dt.datetime:
    repl = current.replace(hour=hour, **kwargs)
    while repl <= current:
        repl = repl + dt.timedelta(days=1)
    return repl

Demo:

>>> now = dt.datetime.utcnow()
>>> now
datetime.datetime(2020, 5, 7, 20, 17, 21, 581402)
>>> next_datetime(now, hour=19)
datetime.datetime(2020, 5, 8, 19, 17, 21, 581402)
>>> next_datetime(now, hour=21)
datetime.datetime(2020, 5, 7, 21, 17, 21, 581402)
>>> next_datetime(now, hour=20, minute=12)
datetime.datetime(2020, 5, 8, 20, 12, 21, 581402)
>>> next_datetime(now, hour=20, minute=50)
datetime.datetime(2020, 5, 7, 20, 50, 21, 581402)

Here **kwargs is designed to take datetime() constructor parameters that are a higher resolution than hour, e.g. minutes, seconds, and microseconds. You may want to provide some validation of that, since passing something like year doesn't make sense given the question.

Related