如何在JSON文件[{"start":"2004-09-8","end":"2005-7-5"}, {"start":"1999-9-7","end":"2000-5-3"}]
中找到两个日期之间的间隔
[{"start":"2004-09-8","end":"2005-7-5"},{"gap":how many days gap"{"start":"1999-9-7","end":"2000-5-3"}]
import json
from collections import defaultdict
res = defaultdict(list)
with open(r'/home/vijaya/Documents/task43.json','r') as list:
data = json.load(list)
print(data)
答案 0 :(得分:1)
您可以只使用datetime
并仅检查timedelta
,
>>> import datetime
>>> data = [{'start': '2004-09-8', 'end': '2005-7-5'}, {'start': '1999-9-7', 'end': '2000-5-3'}]
>>>
>>>
>>> for d in data:
... start = datetime.datetime.strptime(d['start'], '%Y-%m-%d')
... end = datetime.datetime.strptime(d['end'], '%Y-%m-%d')
... d['gap'] = '{} days'.format((end-start).days)
...
>>> data
[{'start': '2004-09-8', 'end': '2005-7-5', 'gap': '300 days'}, {'start': '1999-9-7', 'end': '2000-5-3', 'gap': '239 days'}] # gap is in days
我真的建议您使用pendulum进行日期时间操作。这是一个很棒的模块:)
根据最近的要求,我已经更新了代码,
$ cat datediff.py
from datetime import datetime as dt
data = [ { "start":"2002-08-01", "end":"2004-09-12" }, { "start" :"1998-09-12", "end" : "2001-10-11" }, { "start":"1997-08-01", "end":"1998-01-12" }, { "start" :"1995-09-12", "end" : "1997-7-11" } ]
req_data = []
for first, second in zip(data, data[1:]):
days = (dt.strptime(first['start'], '%Y-%m-%d') - dt.strptime(second['end'], '%Y-%m-%d')).days
if days <= 0:
days = (dt.strptime(second['start'], '%Y-%m-%d') - dt.strptime(first['end'], '%Y-%m-%d')).days
req_data.append(first)
req_data.append({'days': days})
req_data.append(second)
print(req_data)
输出:
$ python datediff.py
[{'start': '2002-08-01', 'end': '2004-09-12'}, {'days': 294}, {'start': '1998-09-12', 'end': '2001-10-11'}, {'days': 243}, {'start': '1997-08-01', 'end': '1998-01-12'}, {'days': 21}, {'start': '1995-09-12', 'end': '1997-7-11'}]