How to get the sum of timedelta in Python?

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

    (Edit: Assuming that by "sum timedelta" you mean "convert a timedelta to int seconds".)

    This is very inefficient, but it is simple:

    int((datetime.datetime.fromtimestamp(0) + myTimeDelta).strftime("%s"))
    

    This converts a Unix timestamp (0) into a datetime object, adds your delta to it, and then converts back to a Unix time. Since Unix time counts seconds, this is the number of seconds your timedelta represented.

提交回复
热议问题