如何通过比较列表中的元素来比较单个 json 文件中的日期?

问题描述 投票:0回答:1

我遇到了问题,基本上我有一个包含具有相同键的数据的 json 文件,它完全是一本字典,我的目标是检查和比较它们之间的日期/时间差异,帮帮我,我快疯了,我'我缺少一些东西,我发布了 json 文件和 Python 代码,非常感谢你,你太棒了。

附言: 抱歉我的英语不好,我使用谷歌翻译。

文件data.json:

[{
    "Day": "Giornata 29",
    "Matches": {
        "Home": "Egnatia",
        "Away": "Kukesi",
        "Times": "19.03. 15:00",
        "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
    }
},{
    "Day": "Giornata 29",
    "Matches": {
        "Home": "Egnatia",
        "Away": "Kukesi",
        "Times": "20.03. 16:09",
        "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
    }
},{
    "Day": "Giornata 41",
    "Matches": {
        "Home": "Lincoln",
        "Away": "Leyton Orient",
        "Times": "19.03. 16:00",
        "Championship": "CALCIO\nINGHILTERRA League One\n2023/2024"
    }
},
{
    "Day": "Giornata 30",
    "Matches": {
        "Home": "Napoli",
        "Away": "Atalanta",
        "Times": "30.03. 12:30",
        "Championship": "CALCIO\nITALIA Serie A\n2023/2024"
    }
}]

Python 代码:

from datetime import datetime, date, timedelta
import time
import json

with open('data.json', 'r+') as f:
    fileData = json.load(f)
    f.close()



day = datetime.now().strftime('%d.%m. %H:%M')

championship = set([d['Matches']['Championship'] for d in fileData])
day= set([q['Day'] for q in fileData])
time = set([s['Matches']['Times'] for s in fileData])

championshipList = [[d for d in fileData if d['Matches']['Championship'] == a] for a in championship]

dayList = [[e for e in fileData if e['Day'] == h] for h in day]

timeList = [[w for w in fileData if w['Matches']['Times'] == c] for c in time]

基本上,我要先检查“Day”键,然后检查“Championship”键,然后我还要检查“Times”键并相互比较,我想得到彼此的时间差,比如天、分钟或小时,你有什么建议吗?

json python-3.x dictionary
1个回答
0
投票

假设您想先检查

Day
,然后检查
Championship
,然后检查
Times
,此代码会为您执行此操作,然后打印时差。我添加了评论来解释它的作用。

import collections
import datetime
import json

with open('data.json', 'r+') as f:
    fileData = json.load(f)
    # no f.close() is needed as the context manager handles this

# create a default dictionary with nested default dictionary that has a list in it
similar = collections.defaultdict(lambda : collections.defaultdict(list))

for file in fileData:
    # for every file put it into the dictionary based on the day and the championship
    similar[file["Day"]][file["Matches"]["Championship"]].append(file)

# make a dictionary from the defaultdict
championships = {k:dict(v) for k,v in similar.items()}

# loop over the days
for day in championships:
    # loop over the championships
    for championship in championships.get(day):
        # get the values
        values = championships.get(day).get(championship)
        # extract the times and parse the string to a timestamp and sort the list
        times = sorted([datetime.datetime.strptime(val.get("Matches").get("Times"), "%d.%m. %H:%M") for val in values])
        # calculate the time difference for every element and its adjacent element
        # if the list has one or no elements return None
        time_difference = None if len(times) <= 1 else list(map(lambda t: t[-1]-t[0], zip(times, times[1:])))
        print(day, championship, time_difference)

您可以格式化时差的输出。

© www.soinside.com 2019 - 2024. All rights reserved.