Python find index of all dates between two dates
Question: I am trying to implement equivalent of `numpy.where` for dates as follows:

    
    
    from datetime import date, timedelta as td, datetime
    d1 = datetime.strptime('1/1/1995', "%m/%d/%Y")
    d2 = datetime.strptime('12/31/2015', "%m/%d/%Y")
    
    AllDays = []
    while(d1<=d2):
        AllDays.append(d1)
        d1 = d1 + td(days=1)
    
    validDate = AllDays
    trainStDt = '1/1/1995'
    trainEnDt = '12/31/2013'
    testStDt = '1/1/2014'
    testEnDt = '12/31/2015'
    
    indTrain = (validDate >= datetime.strptime(trainStDt,'%m/%d/%Y')) & (validDate <=
                                                                               datetime.strptime(trainEnDt,'%m/%d/%Y'))
    indTest = (validDate >= datetime.strptime(testStDt,'%m/%d/%Y')) & (validDate <=
                                                                              datetime.strptime(testEnDt,'%m/%d/%Y'))
    trainDates = validDate[indTrain]
    testDates = validDate[indTest]
    
    print trainDates[0]
    print trainDates[-1:]
    print testDates[0]
    print testDates[-1:]
    

However: (1) indTrain doesn't work as it is trying to compare list to datetime
(2) my solution is to loop through each element of validDates

Is there a better way to do it?


Answer: Just turn your list into an array. Add `import numpy as np` to the top of your
script, and after your `while` loop, add:

    
    
    AllDays = np.array(AllDays)
    

