Python 如何将日期时间舍入到特定时间?

Python 如何将日期时间舍入到特定时间?,python,datetime,timezone,Python,Datetime,Timezone,给定datetime对象,如何将其取整到下一次出现的太平洋标准时间上午8点?我根据评论中的一些想法做出了回答: def nextDay(d): pstTime = d.astimezone(pytz.timezone('US/Pacific')) pstTime = pstTime.replace(hour=8, minute=0, second=0, microsecond=0) if pstTime < d: pstTime += dateti

给定datetime对象,如何将其取整到下一次出现的太平洋标准时间上午8点?

我根据评论中的一些想法做出了回答:

def nextDay(d):
    pstTime = d.astimezone(pytz.timezone('US/Pacific'))
    pstTime = pstTime.replace(hour=8, minute=0, second=0, microsecond=0)

    if pstTime < d:
        pstTime += datetime.timedelta(days=1)

    return pstTime
def下一天(d):
pstime=d.astimezone(pytz.timezone(“美国/太平洋”))
pstTime=pstTime.replace(小时=8,分钟=0,秒=0,微秒=0)
如果时间
只需测试时间是在8之前还是之后,然后在8之后添加一天,并构建一个新的日期时间

import datetime

def round_datetime(dt):
    t = datetime.time(8)
    # If time is after 8am, add a day.
    if dt.time() > datetime.time(8):
        dt += datetime.timedelta(days=1)
    return datetime.datetime.combine(dt, t)

如果结果是具有非固定UTC偏移量的时区中的时区感知datetime对象,则不能仅调用
.replace()
.combine()
——它可能会创建具有错误UTC偏移量的日期时间。该问题类似于(
00:00
用于代替
08:00

假设8AM在PST中始终存在且明确:

from datetime import datetime, time as datetime_time, timedelta
import pytz # $ pip install pytz

def next_8am_in_pst(aware_dt, tz=pytz.timezone('America/Los_Angeles')):
    pst_aware_dt = tz.normalize(aware_dt.astimezone(tz)) # convert to PST
    naive_dt = round_up_to_8am(pst_aware_dt.replace(tzinfo=None))
    return tz.localize(naive_dt, is_dst=None)

def round_up_to_8am(dt):
    rounded = datetime.combine(dt, datetime_time(8))
    return rounded + timedelta(rounded < dt)

创建一个新的datetime,使用当前datetime年、月、日的输入,并将小时、分钟、秒设置为8、0、0respectively@Ian当前位置永远是今天上午8点。要始终进行汇总,您需要在顶部添加另一天,除非它是在上午8点之前。相关:谢谢,我不知道您可以这样分割日期和时间。如果输入是时区感知的datetime对象,那么它会更复杂(如果输入是一个朴素的datetime对象,您的代码就可以了)。它可能会在日期和DST TransitionAnks之间发生故障,这可以跨越夏令时的界限。
>>> str(next_8am_in_pst(datetime.now(pytz.utc))) 
'2016-02-25 08:00:00-08:00'