本文介绍了平均日期数组计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取以下日期的平均值。我考虑过将所有数据转换为秒,然后将其平均。但是可能有更好的方法。

I would like to get the mean of the following dates. I thought about converting all the data to seconds and then averaging them. But there is probably a better way to do it.

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)


推荐答案

在NumPy中,所有 datetime64 [s] 在内部由8字节整数表示。
整数表示自新纪元以来的秒数。

In NumPy all datetime64[s]s are internally represented by 8-byte integers.The ints represent the number of seconds since the Epoch.

因此您可以转换日期列表到 datetime64 [s] dtype的NumPy数组,
将其视为dtype i8 (8字节)整数),取均值,然后将整数转换回 datetime64 [s]

So you could convert the date list to a NumPy array of datetime64[s] dtype,view it as dtype i8 (8-byte ints), take the mean, and then convert the int back into a 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

这篇关于平均日期数组计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:06