日期时间lis的平均时间

2024-06-01 02:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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")

Tags: 对象import列表datetimedefas时间解决方案
3条回答

我也在找,但后来发现了这个。 获取datetime对象列表平均值的非常简单的方法。

    import datetime
    #from datetime.datetime import timestamp,fromtimestamp,strftime ----> You can use this as well to remove unnecessary datetime.datetime prefix :)  
    def easyAverage(datetimeList): ----> Func Declaration
        sumOfTime=sum(map(datetime.datetime.timestamp,datetimeList))
        '''
         timestamp function changes the datetime object to a unix timestamp sort of a format.
         So I have used here a map to just change all the datetime object into a unix time stamp form , added them using sum and store them into sum variable.
        '''
        length=len(datetimeList) #----> Self Explanatory

        averageTimeInTimeStampFormat=datetime.datetime.fromtimestamp(sumOfTime/length)
        '''
        fromtimestamp function returns a datetime object from a unix timestamp.
        '''

        timeInHumanReadableForm=datetime.datetime.strftime(averageTimeInTimeStampFormat,"%H:%M:%S") #----> strftime to change the datetime object to string.
        return timeInHumanReadableForm

或者你可以在一行中完成所有这些:

    avgTime=datetime.datetime.strftime(datetime.datetime.fromtimestamp(sum(map(datetime.datetime.timestamp,datetimeList))/len(datetimeList)),"%H:%M:%S")

干杯

这里有一个简短而甜蜜的解决方案(也许不是最快的)。它获取日期列表中每个日期与某个任意引用日期(返回datetime.timedelta)之间的差异,然后将这些差异相加并求其平均值。然后再加回原来的参考日期。

import datetime
def avg(dates):
  any_reference_date = datetime.datetime(1900, 1, 1)
  return any_reference_date + sum([date - any_reference_date for date in dates], datetime.timedelta()) / len(dates)

有更好的方法来解决这个问题

生成日期时间示例

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

平均2000万次

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和pandas 0.13作为to_timedelta部分,很快就会出现)

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 [32]: int((i.hour*3600+i.minute*60+i.second).mean())
Out[32]: 43152

相关问题 更多 >