2016-02-24 134 views
2

我希望得到以下日期的平均值。我想過將所有數據轉換爲秒,然後對它們進行平均。但是,可能有更好的方法來做到這一點。平均日期排列計算

date = ['2016-02-23 09:36:26', '2016-02-24 10:00:32', '2016-02-24 11:28:22', '2016-02-24 11:27:20', '2016-02-24 11:24:15', '2016-02-24 11:20:25', '2016-02-24 11:17:43', '2016-02-24 11:12:03', '2016-02-24 11:09:11', '2016-02-24 11:08:44', '2016-02-24 11:05:28', '2016-02-24 11:03:23', '2016-02-24 10:58:08', '2016-02-24 10:53:59', '2016-02-24 10:49:34', '2016-02-24 10:43:33', '2016-02-24 10:35:27', '2016-02-24 10:31:50', '2016-02-24 10:31:17', '2016-02-24 10:30:05', '2016-02-24 10:29:21'] 

討厭的溶液:

import datetime 
import time 
import numpy as np 

date = ['2016-02-23 09:36:26', '2016-02-24 10:00:32', '2016-02-24 11:28:22', '2016-02-24 11:27:20', '2016-02-24 11:24:15', '2016-02-24 11:20:25', '2016-02-24 11:17:43', '2016-02-24 11:12:03', '2016-02-24 11:09:11', '2016-02-24 11:08:44', '2016-02-24 11:05:28', '2016-02-24 11:03:23', '2016-02-24 10:58:08', '2016-02-24 10:53:59', '2016-02-24 10:49:34', '2016-02-24 10:43:33', '2016-02-24 10:35:27', '2016-02-24 10:31:50', '2016-02-24 10:31:17', '2016-02-24 10:30:05', '2016-02-24 10:29:21'] 
sec = [time.mktime(datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S").timetuple()) for d in date] 
mean = datetime.datetime.fromtimestamp(np.mean(sec)) 
print(mean) 
+0

我會做完全按照自己的建議。 – ppaulojr

+0

我同意@ppaulojr。將它們轉換爲單位並對其進行平均。 – Matt

+0

看看這個問題http://stackoverflow.com/questions/19681703/average-time-for-datetime-list – ppaulojr

回答

4

在NumPy的所有datetime64[s] s的內部由8字節整數表示。 整數代表自Epoch以來的秒數。

所以,你可以在date列表轉換爲datetime64[s] D型的NumPy的陣列, 認爲這是D型i8(8字節整數),取均值,然後轉換INT回一個datetime64[s]


import numpy as np 

date = ['2016-02-23 09:36:26', '2016-02-24 10:00:32', '2016-02-24 11:28:22', '2016-02-24 11:27:20', '2016-02-24 11:24:15', '2016-02-24 11:20:25', '2016-02-24 11:17:43', '2016-02-24 11:12:03', '2016-02-24 11:09:11', '2016-02-24 11:08:44', '2016-02-24 11:05:28', '2016-02-24 11:03:23', '2016-02-24 10:58:08', '2016-02-24 10:53:59', '2016-02-24 10:49:34', '2016-02-24 10:43:33', '2016-02-24 10:35:27', '2016-02-24 10:31:50', '2016-02-24 10:31:17', '2016-02-24 10:30:05', '2016-02-24 10:29:21'] 

mean = (np.array(date, dtype='datetime64[s]') 
     .view('i8') 
     .mean() 
     .astype('datetime64[s]')) 

print(mean) 

打印

2016-02-24T09:43:40-0500