piRSquared
piRSquared

Reputation: 294218

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

If I use type on a DataFrame which I know has a datetime index, I get:

In [17]: type(df.index)
Out[17]: pandas.tseries.index.DatetimeIndex

but when I test it, I get:

In [18]: type(df.index) == 'pandas.tseries.index.DatetimeIndex'
Out[18]: False

I know I assumed the type of type is a string, but I really don't know what else to try, and searching has resulted in nothing.

Upvotes: 27

Views: 36642

Answers (5)

Hans
Hans

Reputation: 1789

Another option would be to use pandas's built in type checkers, which might allow you to check the type beyond just the container. E.g.

pd.api.types.is_datetime64_any_dtype(df.index)

vs

pd.api.types.is_datetime64_ns_dtype(df.index)

Upvotes: 0

Daniel Wulf
Daniel Wulf

Reputation: 21

In : type(df.index)  
Out: pandas.core.indexes.datetimes.DatetimeIndex


In : type(df.index) == pd.core.indexes.datetimes.DatetimeIndex  
Out: True

Upvotes: 1

Andy Hayden
Andy Hayden

Reputation: 375435

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

Upvotes: 49

Matthew
Matthew

Reputation: 747

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.

Upvotes: 4

M4rtini
M4rtini

Reputation: 13539

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

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

Compare against the object, not a string.

Upvotes: 3

Related Questions