Why can't timedeltas be divided?

Maric Michaud maric at aristote.info
Thu May 25 14:02:15 CEST 2006

oups ididn't post it to the good thread :)

Le Jeudi 25 Mai 2006 01:10, vous avez écrit :
> The ratio of two durations has no meaning???
Oh, sorry, sure it has, I wanted to say "it has no meaning in timedelta 
provided arithmetic".
It's a ratio (no dimension) not a duration. In that sense the expected result 
should be a float, and the proposed operator will break the timedelta's 
arithmetic consistence.

t, u, v <- timedeltas
t+u # valid
t / u # valid
t / u + v # invalid while all terms are valids

It's a big design flaw and I think it's the full answer to the original 

Le Jeudi 25 Mai 2006 02:26, Robert Kern a écrit :
> > what you want is :
> >
> > num_weeks = time_diff.days / 7
> > or
> > num_weeks = (time_diff / 7).days
> Uh, no. Besides the integer division problem in your first line, keep in
> mind that the .days attribute does not give you the time interval measured
> in days. It gives you the number of *whole* days in the interval. The first
> method will be incorrect if time_diff is not an even multiple of 1 day.
> The latter will be incorrect if time_diff is not an even multiple of 7 days.
In fact i was computing the exact number of whole weeks in the delta. In 
respect of that both expression are perfectly correct, but the second one 
isn't clear IMO (why this "days" attribute should give me the number of 
weeks ?).

This said it's not hard to figure out the correct expression of the decimal 
value of weeks in deltas (discarding the microseconds which are not 
relevant) :
num_weeks = (time_diff.days * 24* 3600 + time_diff.seconds) / (7.*24*3600)

If I need to do much of these in a piece of code I would probably define some 
helper functions like this :

def tomicroseconds(td) :
        return td.days * 24* 3600 * 10**6 +
                   td.seconds * 10 ** 6 + td.microseconds

def toseconds(td) : return float(tomicroseonds(td)) / 10 ** 6
tominute, tohours, todays, toweeks, etc...

and use float and int / and % operators.
This is an easy and clean implementation IMHO.


Maric Michaud

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097

More information about the Python-list mailing list