Python查找两个日期之间所有日期的索引

时间:2016-05-28 12:22:31

标签: datetime numpy

我正在尝试为日期实现等效的numpy.where,如下所示:

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:]

然而: (1)indTrain没有工作,因为它试图将列表与日期时间进行比较 (2)我的解决方案是循环遍历validDates的每个元素

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

只需将列表转换为数组即可。将import numpy as np添加到脚本顶部,然后在while循环后添加:

AllDays = np.array(AllDays)