我正在搜索连接列表的元素。
例如:
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:])]
我设置2个连续值之间的间隔。
例如 :
它可能看起来interval=[timedelta(0, 0, 297000),timedelta(0, 0, 297000),timedelta(0, 0, 123000),timedelta(0, 1, 300000)]
,我想要间隔的平均值。
答案 0 :(得分:2)
首先,您可以使用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)
答案 1 :(得分:0)
我认为你在寻找这个:
import datetime
import time
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 = [time.mktime(i[0].timetuple()) for i in data]
average = datetime.datetime.fromtimestamp(sum(date)/len(date))
首先将datetime对象转换为Posix time,然后计算平均值并最终将其转换回来。