Numpy 中的直方图日期时间对象

Histogram datetime objects in Numpy

我有一组日期时间对象,我想在 Python 中对它们进行直方图绘制。

Numpy histogram 方法不接受日期时间,抛出的错误是

File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 176, in histogram
mn, mx = [mi+0.0 for mi in range]
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'

除了手动转换日期时间对象之外,还有其他方法可以执行此操作吗?

numpy.histogram 仅适用于数字。当 dt_arraydatetime 对象的数组时,这将为您提供直方图:

to_timestamp = np.vectorize(lambda x: x.timestamp())
time_stamps = to_timestamp(dt_array)
np.histogram(time_stamps)

.timestamp() 方法似乎只适用于 Python 3.3。如果您使用的是旧版本的 Python,则需要直接计算它:

import datetime
import numpy as np

to_timestamp = np.vectorize(lambda x: (x - datetime.datetime(1970, 1, 1)).total_seconds())
from_timestamp = np.vectorize(lambda x: datetime.datetime.utcfromtimestamp(x))

## Compute the histogram
hist, bin_edges = np.histogram(to_timestamp(dates))

## Print the histogram, and convert bin edges back to datetime objects
print hist, from_timestamp(bin_edges)