如何将日期时间舍入到前一个小时?例如:
print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0
向下舍入到前一个小时:
2017-01-11 12:00:00.0
最佳答案
假设您想将舍入为小时,则可以简单地将microsecond
,second
和minute
替换为零:
print(datetime.now().replace(microsecond=0, second=0, minute=0))
如果要四舍五入到上一个小时(如示例
2017-01-11 13:26:12.0
到2017-01-11 12:00:00.0
中所述),则将microsecond
,second
和minute
替换为零,然后减去一小时: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
关于python - 将日期时间舍入到前一个小时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41595754/