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

标签 python datetime numpy histogram

我有一组日期时间对象,我想用 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'

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

最佳答案

.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)

关于python - Numpy 中的直方图日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330389/

相关文章:

python - Numpy:使用池多重处理矩阵乘法

python - 在 Python 中使用自定义顺序对列表进行排序

python - 如何在 Python DataFrame 中的确定行之前添加空行?

php - 在一段时间内使用 DateTime::diff() 与 mysql 记录进行操作

php - 在 php 中使用日期 ('Y-m-d' ) 时如何正确设置给出的时间?

python - 在 Python 中集成离散点

python - 使用 python 脚本缩放 .STL 文件

python - 请解释一下这两个代码之间的区别

android - 如何知道一天在android中何时开始?

python - 如何在Python中将数组拆分为相等长度的容器?