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

新手上路,请多包涵

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

假设如果时间戳为 2017-11-18 0:16 2017-11-18 0:00 2017-11-18 1:56 2017-11-18 2:00

原文由 user123 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 404
2 个回答

我用 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

原文由 Anton vBR 发布,翻译遵循 CC BY-SA 3.0 许可协议

import pandas as pd

pd.Timestamp.now().round('60min').to_pydatetime()

退货:

 datetime.datetime(2018, 2, 23, 0, 0)

原文由 user123 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题