将时间舍入到最接近的小时python [英] Round time to nearest hour python
本文介绍了将时间舍入到最接近的小时python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数据帧中的python中的时间四舍五入到最接近的小时.
I was trying to round off time to the nearest hour in python in a dataframe.
假设时间戳为 2017-11-18 0:16
,则时间戳应为 2017-11-18 0:00
和 2017-11-18 1:56
应该四舍五入为 2017-11-18 2:00
Suppose if a timestamp is 2017-11-18 0:16
it should come as 2017-11-18 0:00
and 2017-11-18 1:56
should round off as 2017-11-18 2:00
推荐答案
我对jpp进行了一些实验,但最终得到了另一种解决方案,因为在23点时加了一个小时使事情崩溃了.
I experimented a bit with jpp but ended up with a different solution as adding one hour at hour 23 crashed the thing.
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
这篇关于将时间舍入到最接近的小时python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文