首页 > 解决方案 > 获取表示 Python 中特定时间最近出现的日期时间对象

问题描述

我想要一个代表给定时间最近发生的日期时间对象。是否有内置的日期时间方法来完成此操作,或者我必须做类似的事情

from datetime import datetime, time

now = datetime.now()
if now.time() < time(6, 30):

查找最近发生的时间 6:30am

标签: pythonpython-datetime

解决方案


我们可以通过指定 acheckHourcheckMinute对照当前的datetime.

如果它更大,那么我们可以datetimecheckHourcheckMinute

如果它不是更大,我们可以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)

推荐阅读