我想得到以下日期的平均值。我考虑过将所有数据转换为秒,然后对它们求平均值。但是可能有更好的方法来做到这一点。
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 :(得分:6)
在NumPy中,所有date
内部由8字节整数表示。
整数表示自纪元以来的秒数。
因此,您可以将datetime64[s]
列表转换为i8
dtype的NumPy数组,
将其视为dtype datetime64[s]
(8字节整数),取均值,然后将int转换回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
打印
private void Timer()//Timer for color refresh
{
aTimer = new System.Timers.Timer(300);
aTimer.Elapsed += ATimer_Elapsed;//new ElapsedEventHandler(Form1_Load);
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void ATimer_Elapsed(object sender, ElapsedEventArgs e)
{
RefreshColor();
}
private void RefreshColor()//Refreshing the color of selected row
{
this.Invoke((MethodInvoker)delegate
{
if (richTextBox1.SelectionBackColor != Color.PaleTurquoise)
{
HighlightCurrentLine();
}
});
}
private void Form1_Load(object sender, EventArgs e)
{
Timer();
RefreshColor();