On Dec 16, 2010, at 5:10 PM, Lorin Rivers wrote:
> 
> I have  a function that I use to round time increments. I just realized it 
> fails when the time rolls over the 24 hour period.
> 
> I also found myself needing to make a second version for rounding to hours. 
> Anyone care to take a stab at fixing it to handle the rollover AND hours?
> 
> def round_off(mins, secs, to_nearest=1):
>    div_result, remainder = divmod(mins, to_nearest)
> 
>    if remainder < 7:       
>        return to_nearest * div_result
>    elif remainder > 7:
>        return to_nearest * (div_result + 1)
>    else:    #remainder == 7 
>        if secs < 30:
>            return to_nearest * div_result
>        else:
>            return to_nearest * (div_result + 1)
> 
> If the the time is 2010, 12, 16, 23, 54 and the to_nearest is 5 (round to 
> nearest 5 minutes), it works. 
> If the time is     2010, 12, 16, 23, 55
> 
> it errors with the message "minutes must be 0..59"
> 
> I use it like this:
> finishtime = lasttime.replace(minute=round_off(lasttime.minute, 
> lasttime.second, to_nearest=5), second=0)
> 
> I'm too tired & ignorant to figure it out.


It's just trying (correctly) to overflow into the hour. Notice that at the 
right time, it can overflow all the way to the year. And if you're rounding 
local time at the boundary of standard/daylight time, it's even tricker.

The easiest way to do something like this is to convert the date-time to 
seconds since the epoch, round it there, and then convert back to 
year-month-etc.

Reply via email to