Why can't timedeltas be divided?

Dan Bishop danb_83 at yahoo.com
Wed May 24 18:07:25 EDT 2006


If I try to write something like:

    num_weeks = time_diff / datetime.timedelta(days=7)

I get:

    TypeError: unsupported operand type(s) for /: 'datetime.timedelta'
and 'datetime.timedelta'

Of course, one could extend the timedelta class to implement division,

    def _microseconds(self):
        return (self.days * 86400 + self.seconds) * 1000000 +
self.microseconds
    def __truediv__(self, other):
        if isinstance(other, datetime.timedelta):
            return self._microseconds() / other._microseconds()
        else:
            return datetime.timedelta(0, 0, self._microseconds() /
other)
    def __floordiv__(self, other):
       if isinstance(other, datetime.timedelta):
          return self._microseconds() // other._microseconds()
       return NotImplemented

but why is a basic arithmetic operation missing from the standard
datetime module?




More information about the Python-list mailing list