Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round time to nearest hour python

I was trying to round off time to the nearest hour in python in a dataframe.

Suppose if a timestamp is 2017-11-18 0:16 it should come as 2017-11-18 0:00 and 2017-11-18 1:56 should round off as 2017-11-18 2:00

like image 418
user123 Avatar asked Feb 22 '18 21:02

user123


People also ask

How do you round datetime to hours?

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 Timedelta?

To round the Timedelta with specified resolution, use the timestamp. round() method.


1 Answers

I experimented a bit with jpp but ended up with a different solution as adding one hour at hour 23 crashed the thing.

from datetime import datetime, timedelta

now = datetime.now()

def hour_rounder(t):
    # Rounds to nearest hour by adding a timedelta hour if minute >= 30
    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
               +timedelta(hours=t.minute//30))

print(now)
print(hour_rounder(now))

Returns:

2018-02-22 23:42:43.352133
2018-02-23 00:00:00
like image 117
Anton vBR Avatar answered Oct 19 '22 14:10

Anton vBR