I want to round a given time to its closest 20-mintue interval.
For example, if given the time below:
| Given | Rounded |
|---|---|
| 12:05 pm | 12:00 pm |
| 12:10 pm | 12:20 pm |
| 12:21 pm | 12:20 pm |
| 12:33 pm | 12:40 pm |
| 12:43 pm | 12:40 pm |
| 12:50 pm | 1:00 pm |
Note: 12:10 pm -> 12:20 pm, round up if it’s in the middle of the 20-min interval.
I have tried using the code from a similar thread, as shown below: (Rounding up to nearest 30 minutes in Python)
from datetime import datetime, timedelta
def ceil_dt(dt, delta):
return dt + (datetime.min - dt) % delta
now = datetime(2023, 2, 24, 12, 21, 00)
print(now)
print(ceil_dt(now, timedelta(minutes=20)))
#ts.round(freq='T') # minute
As you can see, the given time is 12:21:00, but the output is 12:40:00. Instead, I want 12:21:00 to round to 12:20:00. Eventually, the goal is apply this to a datetime column in pandas, let me know if there is an easier method. Thanks!
>Solution :
from datetime import datetime, timedelta
def round_dt(dt, delta):
increase = (datetime.min - dt) % delta
if increase < delta / 2:
return dt + increase
else:
return dt + increase - delta
now = datetime(2023, 2, 24, 12, 21, 00)
print(now)
print(round_dt(now, timedelta(minutes=20)))
to apply it to a dataframe column, you can use functools.partial and .apply