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

5

27

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.

Payton answered 9/1, 2014 at 20:11 Comment(0)
S
49

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
Snowplow answered 9/1, 2014 at 21:41 Comment(1)
I'd like to think I've come a long way since asking this question... (-:Payton
Y
4

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.

Yanyanaton answered 9/1, 2014 at 20:24 Comment(3)
The solution is to not compare against a string, but the objectTitograd
Thank you. I had 2 points of failure. The string bit I was aware of but didn't know what else to try considering I tried to test against pandas.tseries.index.DatetimeIndex. testing against pd.tseries.index.DatetimeIndex which is how I imported it, did the trick.Payton
This doesn't check whether dates is a DatetimeIndex, just that x[0] is a Timestamp... it could be a list or Series etc. with 0th item a Timestamp.Snowplow
T
3
In [102]: type("asd") == str
Out[102]: True

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

Compare against the object, not a string.

Titograd answered 9/1, 2014 at 20:28 Comment(0)
K
1
In : type(df.index)  
Out: pandas.core.indexes.datetimes.DatetimeIndex


In : type(df.index) == pd.core.indexes.datetimes.DatetimeIndex  
Out: True
Karbala answered 5/12, 2020 at 13:5 Comment(0)
V
0

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)
Vociferant answered 15/5 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.