Skip to main content
 首页 » 编程设计

python之将时间舍入到最近的小时python

2025年05月04日13qlqwjy

我试图在数据框中用 python 将时间四舍五入到最接近的小时。

假设如果时间戳是 2017-11-18 0:16 它应该是 2017-11-18 0:00 2017-11-18 1:56 应该四舍五入为 2017-11-18 2:00

请您参考如下方法:

我用 jpp 做了一些实验,但最终得到了一个不同的解决方案,因为在 23 小时添加一小时会导致崩溃。

from datetime import datetime, timedelta 
 
now = datetime.now() 
 
def hour_rounder(t): 
    # Rounds to nearest hour by adding a timedelta hour if minute >= 30 
    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour) 
               +timedelta(hours=t.minute//30)) 
 
print(now) 
print(hour_rounder(now)) 

返回:

2018-02-22 23:42:43.352133 
2018-02-23 00:00:00