python - 获取表示 Python 中特定时间最近出现的日期时间对象
问题描述
我想要一个代表给定时间最近发生的日期时间对象。是否有内置的日期时间方法来完成此操作,或者我必须做类似的事情
from datetime import datetime, time
now = datetime.now()
if now.time() < time(6, 30):
查找最近发生的时间 6:30am
解决方案
我们可以通过指定 acheckHour
并checkMinute
对照当前的datetime
.
如果它更大,那么我们可以datetime
在checkHour
和checkMinute
如果它不是更大,我们可以datetime
为昨天构造相同的对象。
from datetime import datetime, time
from datetime import timedelta
now = datetime.now()
## Set our hour and minutes to check against ##
checkHour = 6
checkMinute = 30
## Construct a datetime object for our checkHour and checkMinute today ##
checkTime = datetime(now.year, now.month, now.day, checkHour, checkMinute)
## If the current time is greater then our checkTime ##
if now > checkTime:
## Construct datetime object for checkHour, checkMinute today ##
most_recent = datetime(now.year, now.month, now.day, checkHour, checkMinute)
else:
## Else return the date of yesterday ##
yesterday = now - timedelta(days=1)
most_recent = datetime(yesterday.year, yesterday.month, yesterday.day, checkHour, checkMinute)
推荐阅读
- apache-spark - Spark SQL 广播提示中间表
- reactjs - 如何将值从组件传递到 Formik 多步表单向导?
- vue.js - formData 不为空,但sails.js 使用 vue.js 获取空 req.body
- python - 如何在 Python 中将一个数字舍入到一半?
- jestjs - @Jest 工具会是测试自动化的好选择吗?如果应用程序是在 JavaScript 框架中开发的
- angular - 用多个异步操作组成一个依赖顺序的 Observable 链
- java - 字段更改的休眠审计日志
- asp.net-mvc-4 - 如何使用 ASP.NET 核心 2.1 将销售标题模型绑定到 SalesOrder 控制器上的销售页脚集合?
- raspberry-pi - 我该如何解决这个问题,树莓派
- java - 从 Java 连接以编写 Janusgraph 以进行远程遍历