Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 593
DougKruger Avatar asked Jan 11 '17 16:01

DougKruger


People also ask

How do you round the date to the nearest hour?

Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.

How do you round date and time?

Rounding Up Date ObjectsRound up to the next closest rounding unit boundary. For example, if the rounding unit is month then next closest boundary of 2000-01-01 is 2000-02-01 00:00:00 .


2 Answers

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
like image 167
Willem Van Onsem Avatar answered Oct 22 '22 01:10

Willem Van Onsem


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)
like image 10
gipsy Avatar answered Oct 22 '22 01:10

gipsy