7

Some Matplotlib methods need days in 'float days format'. datestr2num is a converter function for this, but it falls over with the relevant pandas objects:

In [3]: type(df.index)
Out[3]: pandas.tseries.index.DatetimeIndex
In [4]: type(df.index[0])
Out[4]: pandas.tslib.Timestamp
In [5]: mpl.dates.date2num(df.index)
Out [5]: ...
AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

This provides a usable list of times in 'float days format':

dates = [mpl.dates.date2num(t) for t in df.index]

But is there a better way?

birone
  • 2,039
  • 6
  • 17
  • 18
  • What function do you want to use that needs this? And maybe you can use `mpl.dates.date2num(df.index.to_pydatetime())`? – joris Jan 16 '15 at 23:03
  • Some of the mpl.finance plotting functions use 'float days format' although it seems a shame date2num can't natively deal with pandas DatetimeIndices. But your suggestion works perfectly thanks! (If you put it in an answer I'll tick it :) – birone Jan 17 '15 at 08:29

1 Answers1

11

You can use the to_pydatetime method of the DatetimeIndex (this will convert it to an array of datetime.datetime's, and mpl.dates.date2num will know how to handle those):

mpl.dates.date2num(df.index.to_pydatetime())

The reason that date2num does not natively handle a pandas DatetimeIndex, is because matplotlib does not yet support the numpy datetime64 dtype (which is how the data are stored in a DatetimeIndex).

joris
  • 133,120
  • 36
  • 247
  • 202