Python 将日期时间舍入到前一小时

Python 将日期时间舍入到前一小时,python,datetime,rounding,Python,Datetime,Rounding,如何将日期时间舍入到前一个小时?例如: print datetime.now().replace(microsecond=0) >> 2017-01-11 13:26:12.0 四舍五入到前一小时:2017-01-11 12:00:00.0如果您想四舍五入到前一小时,只需将微秒、秒和分钟替换为零: print(datetime.now().replace(microsecond=0, second=0, minute=0)) 如果要将前一个小时(如示例2017-01-11 13

如何将日期时间舍入到前一个小时?例如:

print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0

四舍五入到前一小时:
2017-01-11 12:00:00.0
如果您想四舍五入到前一小时,只需将
微秒
分钟
替换为零:

print(datetime.now().replace(microsecond=0, second=0, minute=0))

如果要将前一个小时(如示例2017-01-11 13:26:12.0至2017-01-11 12:00:00.0)四舍五入到,将
微秒
分钟
替换为零,然后减去一小时:

from datetime import datetime, timedelta

print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
shell中的示例:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timedelta
>>> print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
2017-01-11 16:00:00
从日期时间导入日期时间
作为pd进口熊猫
currTime=datetime.now()
时间=pd.to_日期时间(currTime.floor('H'))

如果您的日期是2017-01-11 00:11:22,您希望您的日期是前一天吗?你需要考虑夏令时吗?不,我希望它是<代码> 2017~01-11:00: @ Doukrug:我有点困惑:你说你想轮到下一个小时,但是在你的评论中,你似乎只会往下掉。这只是一天开始的情况吗?还是我忽略了什么?
from datetime import datetime, timedelta

n = datetime.now() - timedelta(hours=1)
new_date = datetime(year=n.year, month=n.month, day=n.day, hour=n.hour)