日期时间列表的平均时间 [英] Average time for datetime list

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

问题描述

寻找时间平均问题的最快解决方案。

Looking for fastest solution of time averaging problem.

我有一个datetime对象的列表。需要查找时间的平均值(不包括年,月,日)。
这是我到目前为止所得到的:

I've got a list of datetime objects. Need to find average value of time (excluding year, month, day). Here is what I got so far:

import datetime as dtm
def avg_time(times):
    avg = 0
    for elem in times:
        avg += elem.second + 60*elem.minute + 3600*elem.hour
    avg /= len(times)
    rez = str(avg/3600) + ' ' + str((avg%3600)/60) + ' ' + str(avg%60)
    return dtm.datetime.strptime(rez, "%H %M %S")


推荐答案

解决这个问题

生成数据样本样本

Generate a sample of datetimes

In [28]: i = date_range('20130101',periods=20000000,freq='s')

In [29]: i
Out[29]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00, ..., 2013-08-20 11:33:19]
Length: 20000000, Freq: S, Timezone: None

平均20m次

In [30]: %timeit pd.to_timedelta(int((i.hour*3600+i.minute*60+i.second).mean()),unit='s')
1 loops, best of 3: 2.87 s per loop

结果作为timedelta(注意,这需要numpy 1.7和 to_timedelta 部分的大熊猫0.13,即将到来)

The result as a timedelta (note that this requires numpy 1.7 and pandas 0.13 for the to_timedelta part, coming very soon)

In [31]: pd.to_timedelta(int((i.hour*3600+i.minute*60+i.second).mean()),unit='s')
Out[31]: 
0   11:59:12
dtype: timedelta64[ns]

在秒这将适用于大熊猫0.12,numpy> = 1.6)。

In seconds (this will work for pandas 0.12, numpy >= 1.6).

In [32]: int((i.hour*3600+i.minute*60+i.second).mean())
Out[32]: 43152

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

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