我需要根据日期范围从词典列表中过滤出子词典
这是我的清单:
[{'5-jan-2019': '34'}, {'10-jan-2019': '34'}, {'21-jan-2019': '12'}, {'25-jan-2019': '34'} , {'5-feb-2019': '34'}]
我需要过滤出某个日期范围内的所有子词典,例如
from_date-'5-jan-2019' and to_date-'25-jan-2019'
并将其添加到新词典中
预期结果
{
'5-jan-2019': '34',
'10-jan-2019': '34',
'21-jan-2019': '12',
'25-jan-2019': '34'
}
答案 0 :(得分:2)
您可以使用datetime
模块来利用__lt__
对象的内置比较方法(datatime.datetime
等)
import datetime
data = [{'5-jan-2019': '34'}, {'10-jan-2019': '34'}, {'21-jan-2019': '12'}, {'25-jan-2019': '34'} , {'5-feb-2019': '34'}]
start, end = '5-jan-2019', '25-jan-2019'
def d_form(d):
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
_d, _m, _y = d.split('-')
return datetime.datetime(int(_y), months.index(_m)+1, int(_d))
start, end = d_form(start), d_form(end)
final_result = [i for i in data if start <= d_form(list(i.keys())[0]) <= end]
输出:
[{'5-jan-2019': '34'},
{'10-jan-2019': '34'},
{'21-jan-2019': '12'},
{'25-jan-2019': '34'}]
答案 1 :(得分:1)
您希望datetime.strptime将字符串转换为datetime对象,然后可以将它们相互比较。
from datetime import datetime
lst = [
{'5-jan-2019': '34'},
{'10-jan-2019': '34'},
{'21-jan-2019': '12'},
{'25-jan-2019': '34'},
{'5-feb-2019': '34'},
]
dt_from_str = lambda dt: datetime.strptime(dt, '%d-%b-%Y')
start_date = dt_from_str('5-jan-2019')
end_date = dt_from_str('25-jan-2019')
new_dict = {}
for sub_dict in lst:
for key, val in sub_dict.items():
if start_date <= dt_from_str(key) <= end_date:
new_dict[key] = val
print(new_dict)
输出:
{
'5-jan-2019': '34',
'10-jan-2019': '34',
'21-jan-2019': '12',
'25-jan-2019': '34',
}