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

Python Numpy中的直方图日期时间对象,python,datetime,numpy,histogram,Python,Datetime,Numpy,Histogram,我有一个datetime对象数组,我想用Python对它们进行直方图分析 Numpy方法不接受datetimes,引发的错误为 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.datet

我有一个datetime对象数组,我想用Python对它们进行直方图分析

Numpy方法不接受datetimes,引发的错误为

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'

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

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

to_timestamp = np.vectorize(lambda x: x.timestamp())
time_stamps = to_timestamp(dt_array)
np.histogram(time_stamps)
.timestamp()
方法似乎只在起作用。如果您使用的是较旧版本的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)

你也可以这样做:
np.vectorize(lambda x:int(x.strftime('%s'))
为什么你需要从1970年开始?(即
to_timestamp=np.vectorize(lambda x:(x-datetime.datetime(1970,1,1)).total_seconds()
)看起来像:
to_timestamp=np.vectorize(lambda x:(x-datetime.datetime(1,1)).total_seconds())from_timestamp=np.vectorize(lambda x:(datetime.datetime(1,1,1)+datetime.timedelta(seconds=x))
将更加通用化(处理从第一年开始的日期)