列表中的平均时间增量 [英] Average timedelta in list

查看:69
本文介绍了列表中的平均时间增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to calculate the avarage timedelta between dates in a list. Although the following works well, I'm wondering if there's a smarter way?

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)

推荐答案

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

Btw, if you have a list of timedeltas or datetimes, why do you even do any math yourself?

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)

这篇关于列表中的平均时间增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆