10

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

Yariv
  • 12,223
  • 15
  • 52
  • 72

2 Answers2

14

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.

Wes McKinney
  • 93,141
  • 30
  • 140
  • 108
  • 1
    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. – andreas-h Mar 20 '13 at 14:57
7

I would do this:-

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

using the to_pydatetime() method.

Calvin Cheng
  • 34,202
  • 32
  • 113
  • 164