我想计算列表中日期之间的平均时间增量。
尽管以下方法效果很好,但我想知道是否有更明智的方法?

delta = lambda last, next: (next - last).seconds + (next - last).days * 86400
total = sum(delta(items[i-1], items[i]) for i in range(1, len(items)))
average = total / (len(items) - 1)

最佳答案

顺便说一句,如果您有一个时间增量或日期时间列表,为什么还要自己做任何数学运算呢?

datetimes = [ ... ]

# subtracting datetimes gives timedeltas
timedeltas = [datetimes[i-1]-datetimes[i] for i in range(1, len(datetimes))]

# giving datetime.timedelta(0) as the start value makes sum work on tds
average_timedelta = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)

10-06 03:04