Python获取下一次发生时间的日期时间

sup*_*e73 4 python datetime

我试图找到特定时间发生的下一个日期时间。

例如:

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
Run Code Online (Sandbox Code Playgroud)

我该如何以干净的方式做到这一点?(假设一切都是 UTC)

Bra*_*mon 6

您可以使用datetime.replace()一些日期时间算术:

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
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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)
Run Code Online (Sandbox Code Playgroud)

这里**kwargs设计为采用datetime()比 更高分辨率的构造函数参数hour,例如分钟、秒和微秒。您可能想对此进行一些验证,因为考虑year到这个问题,传递类似的内容是没有意义的。