Generating a List of Weeks for Multiple Years in Python

HeySander
2 min readJan 21, 2023

Introduction:

Working with dates and times is a common task in programming. In this tutorial, I will show you how I generated a list of weeks for multiple years in Python using the datetime module.

Problem:

The problem I was trying to solve was to generate a list of weeks that starts from the current week, and goes on for a certain number of weeks in the future. The list should take into account the number of weeks in the current year, and adjust accordingly for years that have 53 or 51 weeks.

Solution:

To solve this problem, I used the datetime module to get the current week, and used a for loop to iterate through a certain number of weeks in the future. Inside the for loop, I used the datetime module to get the first and last days of the year, and used them to check if the year has 51 or 53 weeks. If the year has 51 or 53 weeks, I adjusted the number of weeks accordingly.

Code:

import datetime

def generate_weeks_year_list(length):
current_week = datetime.datetime.now().isocalendar()[1]
week_list = []
for i in range(current_week, current_week + length):
current_year = datetime.datetime.now().year + (i-1) // 52
first_day_of_year = datetime.date(current_year, 1, 1)
last_day_of_year = datetime.date(current_year, 12, 31)
weeks_in_current_year = 52
if (first_day_of_year.weekday() == 0 and last_day_of_year.weekday() == 1):
weeks_in_current_year = 51
elif (current_year % 4 == 0 and current_year % 100 != 0) or current_year % 400 == 0:
weeks_in_current_year = 53
next_week = i % weeks_in_current_year + 1
week_list.append(next_week)
return week_list

The code snippet is pretty straight forward. We work with the length value, which determines the length of the list and each time the for loop resets to 1, we check the the weeks_in_current_year, which can be 51, 52 or 53 years, depending on the specific year.

--

--

HeySander
0 Followers

I am an entrepreneur and web developer , currently living in the Netherlands. My tools of choice are Python with Django and some good old vanilla JavaScript.