Skip to content

Instantly share code, notes, and snippets.

@makmac213
Created September 13, 2024 10:58
Show Gist options
  • Save makmac213/c5ca0f807b01803954fc3bdfc368cd16 to your computer and use it in GitHub Desktop.
Save makmac213/c5ca0f807b01803954fc3bdfc368cd16 to your computer and use it in GitHub Desktop.
Group week numbers into [group_by_count]
from datetime import date
def group_week_numbers(start_date, end_date, group_by_count):
"""Group week numbers into [group_by_count]"""
initial_weeknum = start_date.isocalendar()[1]
end_weeknum = end_date.isocalendar()[1]
# end year should be from the isocalendar
# example if you use date(2025, 12, 31) isocalendar will be
# 2025 and week 1
end_year = end_date.isocalendar()[0]
# weeks will be the return value
# grouped will be the temporary holder of the grouped week
weeks = []
grouped = []
for year in range(start_date.year, end_year + 1):
# start week number begins with 1, but initial week number
# should be from start date
start_weeknum = 1
if year == start_date.year:
start_weeknum = initial_weeknum
# December 28 is always in the last week of the year.
# If it is the last year get the weeknumber from the
# end date.
last_weeknum = date(year, 12, 28).isocalendar()[1]
if year == end_year:
last_weeknum = end_date.isocalendar()[1]
for i in range(start_weeknum, last_weeknum + 1):
if len(grouped) < group_by_count:
grouped.append((i, year))
else:
weeks.append(grouped)
grouped = []
grouped.append((i, year))
# If grouped still contains any weeks add them to the list
if len(grouped):
weeks.append(grouped)
return weeks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment