12

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,945
  • 19
  • 54
  • 75

3 Answers3

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.

Wes McKinney
  • 101,437
  • 32
  • 142
  • 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
9

I would do this:-

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

using the to_pydatetime() method.

Calvin Cheng
  • 35,640
  • 39
  • 116
  • 167
0

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)
Majo_Jose
  • 744
  • 1
  • 10
  • 24