我有一本约有15,000条记录的字典,其格式如下:
sample = {0: {'Schedule': ['2017-05-11', '2019-04-30', '2018-10-13', '2019-05-31', '', '']},
1: {'Schedule': ['2017-05-09', '2019-05-31', '', '', '2018-10-13', '2019-05-31']},
2: {'Schedule': ['2017-05-02', '2020-02-29', '', '', '2018-10-12', '2020-02-29']}}
现在我必须将1st,3rd和5th日期'Schedule'
与两个datetime对象进行比较,看看是否落在该范围内。我正在执行以下操作,但结果非常缓慢,大约需要20秒。谁能建议一种更有效的搜索方式?
完整的示例代码:
from datetime import datetime
sample = {0: {'Schedule': ['2017-05-11', '2019-04-30', '2018-10-13', '2019-05-31', '', '']},
1: {'Schedule': ['2017-05-09', '2019-05-31', '', '', '2018-10-13', '2019-05-31']},
2: {'Schedule': ['2017-05-02', '2020-02-29', '', '', '2018-10-12', '2020-02-29']}}
start_date = datetime.date(datetime.strptime("2018-10-12","%Y-%m-%d"))
end_date = datetime.date(datetime.strptime("2018-10-16","%Y-%m-%d"))
for k,v in sample.items():
earliest = [dt for dt in [v["Schedule"][0],v["Schedule"][2],v["Schedule"][4]] if dt] #only need to check these 3 starting dates
def check_earliest(_list): #check if any date meets search criteria
for i in _list:
if start_date <= datetime.date(datetime.strptime(i, "%Y-%m-%d")) <= end_date:
return True
if check_earliest(earliest):
print ("Do something here...")
不要使用datetime对象,或开始datetime
在你的字典对象,所以你不必将它们转换只是这种比较。
您不必使用datetime
对象,因为您的日期按YYYY-MM-DD的顺序排列,即ISO 8601定义。这样的日期(如字符串)在字典上按日期的正确顺序可比较。
所以
start_date = "2018-10-12"
end_date = "2018-10-16"
for k,v in sample.items():
sched = v['Schedule']
earliest = [dt for dt in (sched[0], sched[2], sched[4]) if dt]
def check_earliest(l):
for i in l:
if start_date <= i <= end_date:
return True
if check_earliest(earliest):
print("Do something here...")
已经可以正常工作了。
我将在any()
此处使用该函数来测试您的日期,而不是定义自己的函数:
for k, v in sample.items():
sched = v['Schedule']
if any(sched[i] and start_date <= sched[i] <= end_date for i in (0, 2, 4)):
print ("Do something here...")
对于代码的其他区域,将字符串一次解析为date()
实例可能会很有用,而不是在需要对象时使用字符串进行转换。仅出于此处的比较,并不需要。datetime.date()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句