如何将日期时间舍入到前一个小时?例如:
print datetime.now().replace(microsecond=0) >> 2017-01-11 13:26:12.0
向下舍入到前一个小时: 2017-01-11 12:00:00.0
由于要向下舍到小时,你可以简单地替换microsecond
,seconds
并且minutes
所有零:
print(datetime.now().replace(microsecond=0,second=0,minute=0))
如果你想向下舍到先前的小时(如示例说明2017-01-11 13:26:12.0
来2017-01-11 12:00:00.0
)更换了microseconds
,seconds
并minutes
用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