4

Is there a way to directly get the index of a certain datetime within a DateTimeIndex?

I have following toy example code which does what I want after I convert the DateTimeIndex to a list.

import pandas as pd
import datetime

year = 2020
minutesStep = 10
dateTimeStr = "2020-01-01 00:40:00"

datesTimes = pd.date_range(start='1/1/'+str(year), end='1/1/'+str(year+1), freq=str(minutesStep)+'min')
dateTimeObj = datetime.datetime.strptime(dateTimeStr, '%Y-%m-%d %H:%M:%S')

l = datesTimes.tolist()
i = l.index(dateTimeObj)
print i
print datesTimes[i]

This outputs what is expected:

>>> 
4
2020-01-01 00:40:00

However I would like to get the index directly from the DateTimeIndex. Is that possible?

Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59

1 Answers1

5

Getting the index of a particular datetime within a pandas DateTimeIndex is possible using the get_loc function as follows:

j = datesTimes.get_loc(dateTimeObj)
print j
print datesTimes[j]

Which outputs as well what is expected:

>>> 
4
2020-01-01 00:40:00
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59