Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a python numpy arange of datetime

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.

like image 526
Melanie Avatar asked Aug 27 '12 06:08

Melanie


People also ask

Does NumPy have datetime?

Starting in NumPy 1.7, there are core array data types which natively support datetime functionality. The data type is called datetime64 , so named because datetime is already taken by the Python standard library.

Is datetime64 the same as datetime?

NumPy's datetime64 and timedelta64 objectsNumPy has no separate date and time objects, just a single datetime64 object to represent a single moment in time. The datetime module's datetime object has microsecond precision (one-millionth of a second).


2 Answers

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.

like image 160
Arc Shinus Avatar answered Sep 23 '22 14:09

Arc Shinus


See NumPy Datetimes and Timedeltas. Basically, you can represent datetimes in NumPy using the numpy.datetime64 type, which permits you to do ranges of values.

For NumPy 1.6, which has a much less useful datetime64 type, you can use a suitable list comprehension to build the datetimes (see also Creating a range of dates in Python):

base = datetime.datetime(2000, 1, 1) arr = numpy.array([base + datetime.timedelta(hours=i) for i in xrange(24)]) 

This produces

array([2000-01-01 00:00:00, 2000-01-01 01:00:00, 2000-01-01 02:00:00,    2000-01-01 03:00:00, 2000-01-01 04:00:00, 2000-01-01 05:00:00,    2000-01-01 06:00:00, 2000-01-01 07:00:00, 2000-01-01 08:00:00,    2000-01-01 09:00:00, 2000-01-01 10:00:00, 2000-01-01 11:00:00,    2000-01-01 12:00:00, 2000-01-01 13:00:00, 2000-01-01 14:00:00,    2000-01-01 15:00:00, 2000-01-01 16:00:00, 2000-01-01 17:00:00,    2000-01-01 18:00:00, 2000-01-01 19:00:00, 2000-01-01 20:00:00,    2000-01-01 21:00:00, 2000-01-01 22:00:00, 2000-01-01 23:00:00], dtype=object) 
like image 24
nneonneo Avatar answered Sep 22 '22 14:09

nneonneo