Skip to content

Instantly share code, notes, and snippets.

@mdiener21
Last active April 4, 2024 09:05
Show Gist options
  • Save mdiener21/b4924815497a61954a68cfe3c942360f to your computer and use it in GitHub Desktop.
Save mdiener21/b4924815497a61954a68cfe3c942360f to your computer and use it in GitHub Desktop.
Python round minutes to the nearest quarter hour
def round_to_nearest_quarter_hour(minutes, base=15):
"""
Input: A value in minutes.
Return: An integer rounded to the nearest quarter-hour (0, 15, 30, 45) based on the base interval,
with special handling to ensure rounding from 0 up to 7 goes to 0 and 8 to 15 round to 15
Example round_to_nearest_quarter_hour(0) rounds to 0
round_to_nearest_quarter_hour(7) rounds to 0
round_to_nearest_quarter_hour(8) rounds to 15
round_to_nearest_quarter_hour(22) rounds to 15
round_to_nearest_quarter_hour(23) rounds to 30
"""
# Calculate how far into the current quarter we are
fraction = minutes % base
if fraction == 0:
return minutes # Exactly on a quarter hour
elif fraction < (base / 2):
# If before the halfway point, round down
rounded = minutes - fraction
else:
# If at or past the halfway point, round up
rounded = minutes + (base - fraction)
# Ensure the result is always within the hour range
return int(rounded) % 60
def test_round_to_nearest_quarter_hour():
# Test rounding down to the previous quarter
assert round_to_nearest_quarter_hour(1) == 0, "Failed on rounding down to 0"
assert round_to_nearest_quarter_hour(7) == 0, "Failed on rounding down to 0"
assert round_to_nearest_quarter_hour(8) == 15, "Failed on rounding up to 15"
# Test rounding up to the next quarter
assert round_to_nearest_quarter_hour(16) == 15, "Failed on rounding down to 15"
assert round_to_nearest_quarter_hour(22) == 15, "Failed on rounding down to 15"
assert round_to_nearest_quarter_hour(23) == 30, "Failed on rounding up to 30"
# Test on exact quarters
assert round_to_nearest_quarter_hour(15) == 15, "Failed on exact 15"
assert round_to_nearest_quarter_hour(30) == 30, "Failed on exact 30"
assert round_to_nearest_quarter_hour(45) == 45, "Failed on exact 45"
assert round_to_nearest_quarter_hour(52) == 45, "Failed on exact 45"
# Test rounding across hour boundaries
assert round_to_nearest_quarter_hour(53) == 0, "Failed on rounding up to 0"
assert round_to_nearest_quarter_hour(59) == 0, "Failed on rounding up to 0"
assert round_to_nearest_quarter_hour(0) == 0, "Failed on rounding up to 0"
print("All tests passed.")
test_round_to_nearest_quarter_hour()
@phmx17
Copy link

phmx17 commented Aug 24, 2023

Did you test this?

@cwegener
Copy link

cwegener commented Apr 4, 2024

/ operator needs to be replaced with // operator

@mdiener21
Copy link
Author

Updated the function and included some tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment