将日期时间四舍五入到最接近的小时

Rounding datetime to the nearest hour

我有一个与 and this one 非常相似的问题,但我遇到了一些舍入问题。

我有一个来自 netCDF 文件的时间序列,我正在尝试将它们转换为日期时间格式。时间序列的格式为 'days since 1990-01-01 00:00:00'。最终我想要 .strftime('%Y%m%d.%H%M') 格式的输出。例如,我按如下方式读取我的 netCDF 文件

import netCDF4
nc = netCDF4.Dataset(file_name)
time = np.array(nc['time'][:])

然后我有

In [180]: time[0]
Out[180]: 365
In [181]: time[1]
Out[181]: 365.04166666651145

然后我做了

In [182]: start = datetime.datetime(1990,1,1)
In [183]: delta = datetime.timedelta(time[1])
In [184]: new_time = start + delta
In [185]: print(new_time.strftime('%Y%m%d.%H%M'))
19910101.0059

有没有办法将 "round" 精确到小时,这样我就能得到 19910101.0100

我不认为 datetime 提供了舍入时间的方法,您必须自己提供代码来执行此操作。这样的事情应该有效:

def round_to_hour(dt):
    round_delta = 60 * 30
    round_timestamp = datetime.datetime.fromtimestamp(dt.timestamp() + round_delta)
    round_dt = datetime.datetime.fromtimestamp(round_timestamp)

    return round_dt.replace(microsecond=0, second=0, minute=0)

您可以使用datetime.replace(), and round up by adding an hour to the rounded down value using datetime.timedelta(hours=1)向下取整。

import datetime

def round_to_hour(dt):
    dt_start_of_hour = dt.replace(minute=0, second=0, microsecond=0)
    dt_half_hour = dt.replace(minute=30, second=0, microsecond=0)

    if dt >= dt_half_hour:
        # round up
        dt = dt_start_of_hour + datetime.timedelta(hours=1)
    else:
        # round down
        dt = dt_start_of_hour

    return dt

请注意,由于我们使用的是 replace,因此我们未替换的值(如时区 - tzinfo)将被保留。