Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from pandas.DatetimeIndex to numpy.datetime64?

How to convert from pandas.DatetimeIndex to numpy.datetime64?

I get:

>>> type(df.index.to_datetime())
Out[56]: pandas.tseries.index.DatetimeIndex

Is it safe to do numpy.array(datetimeindex,dtype=numpy.datetime64)?

like image 760
Yariv Avatar asked Nov 05 '12 07:11

Yariv


People also ask

What is datetime64 in Numpy?

datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy. datetime64() method. Syntax : numpy.datetime64(date) Return : Return the date in a format 'yyyy-mm-dd'.

What is DateTimeIndex in Python?

DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.


2 Answers

I would do this:-

new_array = np.array(df.index.to_pydatetime(), dtype=numpy.datetime64)

using the to_pydatetime() method.

like image 148
Calvin Cheng Avatar answered Sep 21 '22 15:09

Calvin Cheng


The data inside is of datetime64 dtype (datetime64[ns] to be precise). Just take the values attribute of the index. Note it will be nanosecond unit.

like image 44
Wes McKinney Avatar answered Sep 17 '22 15:09

Wes McKinney