Complete date and time before the previous hour

How to round the date and time to the previous hour? eg:

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

rounded to the previous hour: 2017-01-11 12:00:00.0

+5
source share
2 answers

If you want to round to an hour , you can simply replace minutes , seconds and minutes with zero:

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

If you want to round to the previous hour (as indicated in the example 2017-01-11 13:26:12.0 - 2017-01-11 12:00:00.0 ), you replace microseconds , seconds and minutes with 0 , and then subtract from it hour:

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

Shell example:

 $ 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 
+10
source
 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) 
+2
source

Source: https://habr.com/ru/post/1262646/


All Articles