Round down datetime to previous hour

前端 未结 2 1740
执笔经年
执笔经年 2021-01-03 21:34

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

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

round

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 21:37

    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))
    

    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))
    

    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
    

提交回复
热议问题