13

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

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

is this still true with pandas 0.10.1? pd.date_range("20120101", "20120102").values yields array([1970-01-16 224:00:00, 1970-01-16 248:00:00], dtype=datetime64[ns]), which is not correct.
9

I would do this:-

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

using the to_pydatetime() method.

Comments

1

If your index is supposed to be the date or datetime values, you can convert it to a DatetimeIndex

   df.index = pd.to_datetime(df.index)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.