Round time to nearest hour python

Question:

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

Asked By: user123

||

Answers:

This is one way.

from datetime import datetime

now = datetime.now()

def rounder(t):
    if t.minute >= 30:
        return t.replace(second=0, microsecond=0, minute=0, hour=t.hour+1)
    else:
        return t.replace(second=0, microsecond=0, minute=0)

now           # 2018-02-22 22:03:53.831589
rounder(now)  # 2018-02-22 22:00:00.000000
Answered By: jpp
import pandas as pd

pd.Timestamp.now().round('60min').to_pydatetime()

Returns:

datetime.datetime(2018, 2, 23, 0, 0)
Answered By: user123

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
Answered By: Anton vBR

There is a general function to round a datetime at any time lapse in seconds here

Sample:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
--> 2013-01-01 00:00:00
Answered By: Le Droid

Here is one way to do it (based on another solution provided here)

def round_to_closest_hour(dttm):
    add_hour = True if dttm.minute >= 30 else False
    dttm = dttm.replace(second=0, microsecond=0, minute=0)
    if add_hour:
        dttm += timedelta(hours=1)
    return dttm

Basically, check if an hour is needed to be added or not (depending on whether it’s past 30 minutes mark). Then reset minutes, seconds, microseconds and add an hour if required.

Answered By: exAres
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.