gpt4 book ai didi

python - 将列表(日期时间)的元素求和为一个值

转载 作者:行者123 更新时间:2023-12-01 05:03:34 25 4
gpt4 key购买 nike

我正在搜索以连接列表的元素。

例如:l=[0,1,2,3,4,5,6,7,8,9]

我想要:

l_concatenated=45

我的代码是:

  from datetime import *
data=[[datetime.datetime(2012, 8, 19, 15, 28, 2, 810000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 2, 811000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 108000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 108000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 182000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 182000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 326000), 159],
[datetime.datetime(2012, 8, 19, 15, 28, 3, 326000), 159]]

date=[i[0] for i in data]
interval=[b-a for a,b in zip(date[:-1],date[1:])]
sorted_interval=[item for item in interval if item!=timedelta(0)]
# It doesn't function and just give wrong information
interval_concatenated=[ko[i]+ko[i+1] for i in range(len(sorted_interval)-1)]

编辑:我需要恢复两个日期之间间隔的平均值。使用 interval=[b-a for a,b in zip(date[:-1],date[1:])] 我设置两个连续值之间的间隔。例如 :它可能看起来像 interval=[timedelta(0, 0, 297000),timedelta(0, 0, 297000),timedelta(0, 0, 123000),timedelta(0, 1, 300000)] 和我想要间隔的平均值。

最佳答案

首先,您可以使用 zip 计算连续日期之间的间隔:

intervals = [d2[0] - d1[0] for (d1, d2) in zip(data, data[1:])]

然后,获取总timedelta:

total_interval = sum(intervals, timedelta(0, 0, 0))

最后,计算平均值:

average_interval = total_interval / len(intervals)

关于python - 将列表(日期时间)的元素求和为一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25506417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com