How to get the sum of timedelta in Python?

前端 未结 6 1951
时光说笑
时光说笑 2020-12-06 09:47

Python: How to get the sum of timedelta?

Eg. I just got a lot of timedelta object, and now I want the sum. That\'s it!

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 09:56

    I am pretty sure that by "sum" he means that he wants the value of the sum in a primitive type (eg integer) rather than a datetime object.

    Note that you can always use the dir function to reflect on an object, returning a list of its methods and attributes.

    >>> import datetime
    >>> time_sum=datetime.timedelta(seconds=10) + datetime.timedelta(hours=5)
    >>> time_sum
    datetime.timedelta(0, 18010)
    >>> dir(time_sum)
    ['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__str__', '__sub__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds']
    

    So in this case, it looks like we probably want seconds.

    >>> time_sum.seconds
    18010
    

    Which looks right to me:

    >>> 5*60*60 + 10
    18010
    

提交回复
热议问题