How do I test if an object is a pandas datetime index?

In [102]: type("asd") == str
Out[102]: True

In [103]: type("asd") == "str"
Out[103]: False

Compare against the object, not a string.


What did you import Pandas as?

If you are following the guide in the documentation and did something like:

import pandas as pd
dates = pd.date_range('20130101', periods=6)

type(dates[0]) 
pandas.tslib.TimestampTimestamp('2013-01-01 00:00:00', tz=None)

type(dates[0]) == pandas.tslib.Timestamp
False  
# this throws NameError since you didn't import as pandas

type(dates[0]) == pd.tslib.Timestamp
True  
# this works because we imported Pandas as pd

Out of habit I neglected to mention as @M4rtini highlighted that you should not be using a string to compare equivalency.


You can use isinstance of the DatetimeIndex class:

In [11]: dates = pd.date_range('20130101', periods=6)

In [12]: dates
Out[12]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00, ..., 2013-01-06 00:00:00]
Length: 6, Freq: D, Timezone: None

In [13]: isinstance(dates, pd.DatetimeIndex)
Out[13]: True