我一直在深入研究 List Comprehensions,并決心將其付諸實踐。
下面的代碼需要輸入月份和年份來確定當月的作業日數,減去公共假期(可在https://www.gov.uk/bank-holidays.json獲得)。
此外,我想列出該月/年的所有公共假期,但我對日期格式沖突感到震驚。
TypeError: '<' not supported between instances of 'str' and 'datetime.date'
edate和sdate是 datetime.date,而是title["date"]一個字串。
我已經嘗試過類似的東西datetime.strptime,datetime.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)
uj5u.com熱心網友回復:
我得到了這個作業。您可以使用 datetime 模塊來決議字串格式,但是您需要將該結果轉換為 aDate以與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 ]
uj5u.com熱心網友回復:
首先使用strptime,然后將datetime物件轉換為日期。我不確定是否有更直接的方法,但這似乎可行:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512117.html
標籤:Python日期约会时间
