How can I make a python numpy arange of datetime

Melanie picture Melanie · Aug 27, 2012 · Viewed 70.6k times · Source

I have some input data, with timestamps in the input file in the form of hours from the date time specified in the filename.

This is a bit useless, so I need to convert it to python datetime.datetime objects, and then put it in a numpy array. I could write a for loop, but I'd like to do something like:

numpy.arange(datetime.datetime(2000, 1,1), datetime.datetime(2000, 1,2), datetime.timedelta(hours=1))

which throws a TypeError.

Can this be done? I'm stuck with python 2.6 and numpy 1.6.1.

Answer

Arc Shinus picture Arc Shinus · Dec 17, 2015
from datetime import datetime, timedelta

t = np.arange(datetime(1985,7,1), datetime(2015,7,1), timedelta(days=1)).astype(datetime)

The key point here is to use astype(datetime), otherwise the result will be datetime64.