1

I have a list that contains dates that I created using:

dates_list = pd.date_range(startdate, num_of_periods, freq = 'MS')

^stored the date range in dates_list

This returns my monthly list of dates correctly if I do print(dates_list).

What I am trying to do is looking for an index number given a specific date in the range. I tried:

dates_list.index(call_date)

^^where call_date is the date I am trying to find the index number of

and I get an error message that reads:

TypeError: 'DatetimeIndex' object is not callable

If I try this same command on a simpler list, ie: simple_list = ['cheese', 'banana', 'mushroom', 'apple' ...] simple_list.index('banana') it returns 1.

How do I get the index value from a list of dates? Is there something I have to do differently?

Any feedback would be appreciated. Thank you.

1 Answer 1

2

You have a DatetimeIndex object, not a list. You can confirm this by printing type(dates_list). DatetimeIndex objects do not have an index method.

You can manually retrieve the index as follows:

dates_list = pd.date_range(start=pd.Timestamp('now').normalize(), periods=10, freq='D')

print(dates_list)

# DatetimeIndex(['2018-05-02', '2018-05-03', '2018-05-04', '2018-05-05',
#                '2018-05-06', '2018-05-07', '2018-05-08', '2018-05-09',
#                '2018-05-10', '2018-05-11'],
#               dtype='datetime64[ns]', freq='D')

res = (dates_list == pd.Timestamp('2018-05-04')).argmax()

# 2

Alternatively, you can use a generator. This method is only advisable for large ranges where you believe the date you require is near the start of your DatetimeIndex.

x = pd.Timestamp('2018-05-04')
res = next((i for i, j in enumerate(dates_list) if j == x), None)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.