如何使用 python 将打印结果列表与今天的日期进行比较?



我从一个网站上找到了一个日期列表,并把它们打印了出来。我似乎不知道如何浏览那张日期列表,看看其中是否有与今天的日期相符!

下面是我的代码:

import json
from datetime import date
from urllib.request import urlopen
with urlopen("https://fantasy.premierleague.com/api/bootstrap-static/") as response:
source = response.read()
data = json.loads(source)
today = date.today()
for item in data['events']:
print(item['deadline_time'][0:10])

数据如下:

2021-08-13
2021-08-21
2021-08-28
2021-09-11
2021-09-17
2021-09-25

我对这个项目的最终计划是让python遍历列表,如果任何日期与今天的日期匹配,那么我希望它给我发送一条短信=)

您可以使用str比较,这只需要一个转换date > str

today_as_str = date.today().strftime("%Y-%m-%d")
for item in data['events']:
if item['deadline_time'][0:10] == today_as_str:
print("MATCH")

值得注意的是,您也可以将每个字符串解析为日期时间,但这要花费更多的时间

today = date.today()
for item in data['events']:
if datetime.strptime(item['deadline_time'][0:10], "%Y-%m-%d").date() == today:
print("MATCH")