When fridays_135 is called, a list of dates between the start date and end date is produces by date_range. That list is then narrowed down to just the Friday dates and then grouped by month by fridays_by_month. Finally, fridays_135 loops through those groups of months, extracts the 0th, 2nd, and 4th element in that list, and then appends them to the fri_135 list to produce a list of dates corresponding to the 1st, 3rd, and 5th Friday of ever month within the original date range, ordered by year and then by month.
from datetime import date, timedelta
start_date = date(2021, 1, 1)
end_date = date(2025, 12, 31)
''' Returns a list of dates between two dates (inclusive)'''
def date_range(start = start_date, end = end_date):
delta = end - start
dates = [start + timedelta(days=i) for i in range(delta.days + 1)]
return dates
''' Returns a list of lists containing the Friday dates for each month in a given range'''
def fridays_by_month():
year = range(1, 13)
years = range(start_date.year, end_date.year + 1)
date_range_fris = [date for date in date_range() if date.strftime('%a') == "Fri"]
range_fris = []
for yr in years:
for month in year:
month_fris = []
for date in date_range_fris:
if date.strftime('%m') == str(f'{month:02}') and date.year == yr:
month_fris.append(date)
range_fris.append(month_fris)
month_fris = []
return range_fris
'''Returns a list of first, third, and fifth Fridays of each month in a given range of years, as a string, ordered by year and then by month'''
def fridays_135():
fri_ordinals = [0, 2, 4]
month_fris = fridays_by_month()
fri_135 = []
for month in month_fris:
for index, date in enumerate(month):
if index in fri_ordinals:
fri_135.append(str(date))
return fri_135
print(fridays_135())
start_date = date(2021, 1, 8)
, the first date you produce is'2021-01-08'
. Is that actually correct? That's the month's second Friday... \$\endgroup\$