在Python中将timedelta加在一起

编程入门 行业动态 更新时间:2024-10-28 06:26:09
本文介绍了在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加在一起

本文发布于:2023-10-19 20:36:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   加在   Python   timedelta

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!