Simplify code for Critical Mass

This commit is contained in:
Edward Betts 2023-10-29 15:35:26 +00:00
parent aaa3d71665
commit f866a38add

View file

@ -21,6 +21,7 @@ import pytz
import requests import requests
import yaml import yaml
from dateutil.easter import easter from dateutil.easter import easter
from dateutil.relativedelta import FR, relativedelta
from agenda import thespacedevs from agenda import thespacedevs
@ -307,44 +308,21 @@ def get_us_holidays(input_date: date) -> list[Event]:
] ]
def critical_mass(start_date: date) -> list[Event]: def critical_mass(start_date: date, limit: int = 12) -> list[Event]:
""" """Future dates for Critical Mass."""
Return a list of the next 12 dates of the last Friday of the month on or after a given date.
:param start_date: The date from which to start looking for last Fridays.
:type start_date: date
:return: List of next 12 last Fridays on or after the start_date.
:rtype: List[date]
"""
events: list[Event] = [] events: list[Event] = []
current_date = start_date
# Set current month and year based on the start_date for _ in range(limit):
current_month = start_date.month # Calculate the last Friday of the current month
current_year = start_date.year last_friday = current_date + relativedelta(day=31, weekday=FR(-1))
for _ in range(12):
# Calculate the last day of the current month
if current_month == 12:
last_day_of_month = date(current_year + 1, 1, 1) - timedelta(days=1)
else:
last_day_of_month = date(current_year, current_month + 1, 1) - timedelta(
days=1
)
# Find the last Friday of the current month
last_friday = last_day_of_month
while last_friday.weekday() != 4: # Monday is 0 and Sunday is 6
last_friday -= timedelta(days=1)
# Include it in the list only if it's on or after the start_date # Include it in the list only if it's on or after the start_date
if last_friday >= start_date: if last_friday >= start_date:
events.append(Event(name="critical_mass", date=last_friday)) events.append(Event(name="critical_mass", date=last_friday))
# Move to the next month # Move to the next month
current_month += 1 current_date += relativedelta(months=1)
if current_month == 13:
current_month = 1
current_year += 1
return events return events