Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Round time to the closest 20-minute interval?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading