为什么我不能用float来划分datetime.timedelta?

时间:2012-05-17 12:52:40

标签: python datetime timedelta

>>> 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'

有人知道只允许timedeltas被整数整除的理性吗?

2 个答案:

答案 0 :(得分:5)

实际上非常简单 - 这是一个缺失的功能。

这样做的好处是它已被添加为Python 3.x中的一项功能。

请注意2.x3.x中支持的操作表之间的区别。

答案 1 :(得分:2)

非常有趣 - 我本来希望这也能奏效。我刚刚编写了一个函数,其中包含一些在Python 2.x中执行此操作的示例/ doctests。同时发布为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()