将日期时间舍入到前一个小时 [英] Round down datetime to previous hour
本文介绍了将日期时间舍入到前一个小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将日期时间舍入到前一个小时?例如:
How to round down datetime to previous hour? for example:
print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0
向下舍入到前一个小时: 2017-01-11 12:00:00.0
round down to previous hour: 2017-01-11 12:00:00.0
推荐答案
鉴于您要四舍五入到小时数,您只需替换 microsecond
, second
和分钟
,带有零:
Given you want to round down to the hour, you can simply replace microsecond
, second
and minute
with zeros:
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
并将分钟
设为零,然后减去一小时:
If you want to round down to the previous hour (as stated in the example 2017-01-11 13:26:12.0
to 2017-01-11 12:00:00.0
), replace microsecond
, second
and minute
with zeros, then subtract one hour:
from datetime import datetime, timedelta
print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
shell中的示例:
Example in the 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
这篇关于将日期时间舍入到前一个小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文