首页 > 解决方案 > Python获取下一次发生时间的日期时间

问题描述

我正在尝试查找特定时间发生的 NEXT 日期时间。

例如:

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

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

标签: pythondatetime

解决方案


您可以使用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

演示:

>>> 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)

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


推荐阅读