本文介绍了在Python中将timedelta加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个列表:
[datetime.timedelta(0, 1800), datetime.timedelta(0, 1800), datetime.timedelta(0, 1800), datetime.timedelta(0, 1800)]合起来就是2:00小时.我正在尝试将这些时间加起来以获得2:00时间增量,然后又需要将其转换为2.0小时字符串.最终的倒计时分别是1:30小时为1.5小时.
Collectively that is 2:00 hours. I'm trying to add those up to get 2:00 time delta, which then in turn needs to be turned into a string of 2.0 Hours. Respectively 1:30 Hours would be 1.5 Hours as the final countdown.
推荐答案幼稚的方法是从每个对象中获取 seconds 并对其进行 sum
The naive approach would be to take the seconds from each object and sum them
>>> a = [datetime.timedelta(0, 1800)] * 4 >>> print sum([d.seconds for d in a]) 7200 >>> print sum([d.seconds for d in a]) / 60.0 / 60.0 2.0但这并不像Haidro的解决方案那么强大:
but this is not as robust as Haidro's solution:
import operator reduce(operator.add, a)这会导致 timedelta 对象具有正确的增量,您可以根据需要使用它.
This results in a timedelta object with the correct delta that you can use however you want.
更多推荐
在Python中将timedelta加在一起
发布评论