Numpy Bar Graph datetime objects

I have an array of datetime objects, and I would like their histograms in Python.

Numpy histogram method does not accept datetime data, error was selected

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'

Is there a way to accomplish this otherwise than manually converting a datetime object?

+4
source share
2 answers

numpy.histogramonly works with numbers. When dt_arrayis your array of objects datetime, this will give you a histogram:

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

The method .timestamp()only works with Python 3.3 . If you are using an older version of Python, you will need to calculate it directly:

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)
+7
source

All Articles