通过带有日期的JSON数组列出迭代(日期格式冲突)



我一直在深入研究列表理解,并决心将其付诸实践。

以下代码使用月份和年份输入来确定一个月的工作日数,减去公共假日(可在https://www.gov.uk/bank-holidays.json)。

此外,我想列出该月/年的所有公共假日,但我被日期格式冲突所困扰。

TypeError: '<' not supported between instances of 'str' and 'datetime.date'

edatesdate是datetime.date,而title["date"]是字符串。

我已经尝试过datetime.strptimedatetime.date这样的东西,现在都有效了。

如何解决列表理解中的日期冲突?

感谢对代码的任何帮助或一般反馈。

from datetime import date, timedelta, datetime
import inspect
from turtle import title
from typing import Iterator
import numpy as np
import json
import requests
from calendar import month, monthrange
import print
# Ask for a month and year input (set to September for quick testing)
monthInput = "09"
yearInput = "2022"
# Request from UK GOV and filter to England and Wales
holidaysJSON = requests.get("https://www.gov.uk/bank-holidays.json")
ukHolidaysJSON = json.loads(holidaysJSON.text)['england-and-wales']['events']
# List for all England and Wales holidays
ukHolidayList = []
eventIterator = 0
for events in ukHolidaysJSON:
ukHolidayDate = list(ukHolidaysJSON[eventIterator].values())[1]
ukHolidayList.append(ukHolidayDate)
eventIterator += 1
# Calculate days in the month
daysInMonth = monthrange(int(yearInput), int(monthInput))[1] # Extract the number of days in the month
# Define start and end dates
sdate = date(int(yearInput), int(monthInput), 1)   # start date
edate = date(int(yearInput), int(monthInput), int(daysInMonth))   # end date
# Calculate delta
delta = edate - sdate
# Find all of the business days in the month
numberOfWorkingDays = 0
for i in range(delta.days + 1):  # Look through all days in the month
day = sdate + timedelta(days=i)
if np.is_busday([day]) and str(day) not in ukHolidayList: # Determine if it's a business day
print("- " + str(day))
numberOfWorkingDays += 1
# Count all of the UK holidays
numberOfHolidays = 0
for i in range(delta.days + 1):  # Look through all days in the month
day = sdate + timedelta(days=i)
if str(day) in ukHolidayList: # Determine if it's a uk holiday
numberOfHolidays += 1
# Strip the 0 from the month input
month = months[monthInput.lstrip('0')]
# for x in ukHolidaysJSON:
#     pprint.pprint(x["title"])
# This is where I've gotten to
hols = [ title["title"] for title in ukHolidaysJSON if title["date"] < sdate and title["date"] > edate ]

print(hols)

我开始工作了。您可以使用datetime模块来解析字符串格式,但需要将结果转换为Date,以便与现有的Date对象进行比较。

hols = [ title["title"] for title in ukHolidaysJSON if datetime.strptime(title["date"], '%Y-%m-%d').date() < sdate and datetime.strptime(title["date"], "%Y-%m-%d").date() > edate ]

首先使用strptime,然后将datetime对象转换为date。我不确定是否有更直接的方法,但这似乎有效:

hols = [title["title"] for title in ukHolidaysJSON
if datetime.strptime(title["date"], "%Y-%M-%d").date() < sdate and
datetime.strptime(title["date"], "%Y-%M-%d").date() > edate]

最新更新