python - 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)
解决方案
您可以使用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
考虑到问题,传递类似的东西没有意义。
推荐阅读
- android - 从 iOS 和 android 上传的图像是不同的
- iterm2 - 粘贴大量代码时,Iterm2 奇怪/重复/丢失的字符
- python-3.x - xpath:如何提取“强”标签中的文本?
- java - 使用同步块等待结果导致应用程序冻结
- arduino - 如何解析 SIM808 原始 GPS 数据?
- scala - Scala 2.12 与 java 1.8 互操作不能编译为 twitter finagle 代码
- ecmascript-6 - 绑定函数是否支持 ES6 中的正确尾调用?
- vue.js - 在axios GET之后chartJS饼图没有更新
- matlab - 计算矩阵中的孤岛(最好在 IDL 中)
- javascript - Node JS 嵌套查询中的执行顺序