How to get the sum of timedelta in Python?

前端 未结 6 1939
时光说笑
时光说笑 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:52

    datetime combine method allows you to combine time with a delta

    datetime.combine(date.today(), time()) + timedelta(hours=2)
    

    timedelta can be combined using usual '+' operator

    >>> timedelta(hours=3) 
    datetime.timedelta(0, 10800)
    >>> timedelta(hours=2)
    datetime.timedelta(0, 7200)
    >>>
    >>> timedelta(hours=3) + timedelta(hours=2)
    datetime.timedelta(0, 18000)
    >>> 
    

    You can read the datetime module docs and a very good simple introduction at

    • http://www.doughellmann.com/PyMOTW/datetime/

提交回复
热议问题