获取代表Python中特定时间的最新出现的datetime对象

问题描述

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

from datetime import datetime,time

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

查找上午6:30的最近一次事件

解决方法

我们可以通过指定checkHourcheckMinute并将其与当前datetime进行比较来做到这一点。

如果更大,则可以在datetimecheckHour的今天构造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,checkMinute)
else:

    ## Else return the date of yesterday ##

    yesterday = now - timedelta(days=1)
    most_recent = datetime(yesterday.year,yesterday.month,yesterday.day,checkMinute)