Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I divide a datetime.timedelta by a float?

>>> import datetime
>>> now1 = datetime.datetime.now()
>>> now2 = datetime.datetime.now()
>>> timedelta = now2-now1
>>> halfdt = timedelta/2  #This works just fine
>>> halfdt = timedelta/2. #TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'float'

Does anybody know the rational for only allowing timedeltas to be divisible by integers?

like image 853
mgilson Avatar asked May 17 '12 12:05

mgilson


2 Answers

It's actually pretty simple - it was a missing feature.

The upside of this is that it's been added as a feature in Python 3.x.

Note the difference between the supported operation tables in 2.x and 3.x.

like image 179
Gareth Latty Avatar answered Oct 17 '22 02:10

Gareth Latty


Very interesting -- I would have expected that to work too. I just wrote a function with some examples/doctests that does this in Python 2.x. Also posted as an ActiveState recipe:

import datetime

def divide_timedelta(td, divisor):
    """Python 2.x timedelta doesn't support division by float, this function does.

    >>> td = datetime.timedelta(10, 100, 1000)
    >>> divide_timedelta(td, 2) == td / 2
    True
    >>> divide_timedelta(td, 100) == td / 100
    True
    >>> divide_timedelta(td, 0.5)
    datetime.timedelta(20, 200, 2000)
    >>> divide_timedelta(td, 0.3)
    datetime.timedelta(33, 29133, 336667)
    >>> divide_timedelta(td, 2.5)
    datetime.timedelta(4, 40, 400)
    >>> td / 0.5
    Traceback (most recent call last):
      ...
    TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'float'

    """
    # timedelta.total_seconds() is new in Python version 2.7, so don't use it
    total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6
    divided_seconds = total_seconds / float(divisor)
    return datetime.timedelta(seconds=divided_seconds)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
like image 30
Ben Hoyt Avatar answered Oct 17 '22 03:10

Ben Hoyt