【发布时间】:2019-04-24 09:01:38
【问题描述】:
我有下一本字典,我需要获取确定时期之间的缺失时期,换句话说,获取一个时期的结束日期和下一个时期的开始日期之间的时期。
{'0': {'enddate': u'2015/08/31',
'startdate': u'2015/01/01'},
'1': {'enddate': u'2018/10/31',
'startdate': u'2017/01/01'},
'2': {'enddate': u'2019/03/29',
'startdate': u'2019/01/01'}}
The function who get this data is the next:
def periods(periods):
total_periods={}
for period in periods:
total_periods[period] = {}
for startdate in periods[period][0]:
total_periods[period]['startdate'] = startdate
for enddate in periods[period][-1]:
total_periods[period]['enddate'] = enddate
I have the next code that get the missing periods but i cant to order whith my expect results.
gaps={}
s=[]
e=[]
for i in period:
s.append(datetime.strftime(datetime.strptime(period[i]['enddate'],'%Y/%m/%d')+timedelta(days=1),'%Y/%m/%d'))
e.append(datetime.strftime(datetime.strptime(period[i]['startdate'],'%Y/%m/%d')+timedelta(days=-1),'%Y/%m/%d'))
for i in range(len(s)):
if i==len(s)-1:
break
d={}
d['startdate']=s[i]
d['enddate']=e[i+1]
gaps[str(i)]=d
The output of these code is the next:
{'0': {'enddate': '2014/12/31', 'startdate': '2018/11/01'},
'1': {'enddate': '2018/12/31', 'startdate': '2015/09/01'}}
但是错了,因为我需要下一个结果:
{'0': {'enddate': '2016/12/31', 'startdate': '2015/09/01'},
'1': {'enddate': '2018/12/31', 'startdate': '2018/11/01'}}
希望我解释正确和清楚。
提前致谢
【问题讨论】:
标签: python python-3.x dictionary