2 回答
TA贡献1806条经验 获得超8个赞
您希望 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',
}
TA贡献1827条经验 获得超7个赞
您可以使用该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'}]
添加回答
举报