Use timedelta floor division for whole intervals
Use timedelta floor division for whole intervals
When a duration must be split into complete fixed intervals plus a leftover, operate on timedelta values directly. Here, the input duration is 5 hours, 59 minutes, and 59 seconds. divmod(elapsed, interval) returns the integer quotient 23 and the remaining timedelta of 14 minutes, 59 seconds. The reconstruction assertion confirms that this quotient and remainder describe this particular input exactly.
This is clearer than converting the duration to a floating-point number of minutes and casting it to int. timedelta floor division by another timedelta computes the floor and returns an integer; modulo returns the residual duration. Because the quotient is floor-based, a negative elapsed value follows Python floor semantics rather than truncation toward zero. That may be appropriate for bucket calculations, but it should be an explicit product decision when negative values are possible.
Use a positive, nonzero interval. A zero divisor raises ZeroDivisionError, and this pattern models equal-length elapsed intervals, not calendar months or local clock schedules. Python 3.2 added timedelta floor division and remainder operations between timedeltas, along with divmod() support. The official timedelta documentation describes the supported operations, returned types, and version change.
AI-assistance disclosure: AI helped draft this educational example; the assertions check only the displayed interval arithmetic.
from datetime import timedelta
elapsed = timedelta(hours=5, minutes=59, seconds=59)
interval = timedelta(minutes=15)
whole_intervals, remainder = divmod(elapsed, interval)
assert whole_intervals == 23
assert remainder == timedelta(minutes=14, seconds=59)
assert whole_intervals * interval + remainder == elapsed
print(f"whole={whole_intervals}")
print(f"remainder={remainder}")
whole=23
remainder=0:14:59
Comments
Post a Comment