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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41595754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:17:55  来源:igfitidea点击:

Round down datetime to previous hour

pythondatetimerounding

提问by DougKruger

How to round down datetime to previous hour? for example:

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

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

round down to previous hour: 2017-01-11 12:00:00.0

向下舍入到前一小时: 2017-01-11 12:00:00.0

回答by Willem Van Onsem

Given you want to round down to the hour, you can simply replace microsecond, secondand minutewith zeros:

鉴于您想四舍五入到 hour,您可以简单地替换microsecond,secondminute用零:

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


If you want to round down to the previoushour (as stated in the example 2017-01-11 13:26:12.0to 2017-01-11 12:00:00.0), replace microsecond, secondand minutewith zeros, then subtract one hour:

如果你想向下舍到先前的小时(如示例中陈述2017-01-11 13:26:12.02017-01-11 12:00:00.0),更换microsecondsecondminute用零,则减一小时:

from datetime import datetime, timedelta

print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))

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

回答by gipsy

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)