How to Extract and Handle Week Numbers from Dates in Python

How to Extract and Handle Week Numbers from Dates in Python

Week numbers are a useful way to represent dates, especially for business and project planning. In Python, extracting and handling week numbers from dates can be accomplished using the datetime module and its various methods.

Understanding Week Numbers and ISO 8601

Before we examine the code, let’s briefly understand what week numbers are and how they’re determined. A week number represents the ordinal number of the week within a year. The first week of the year is assigned the number 1, the second week is 2, and so on. However, there are different standards for determining the first week of the year, with ISO 8601 being a commonly used international standard.

Here’s a summary of the ISO 8601 standard for week numbering:

  • The first week of the year is the week that contains the first Thursday of the year (or alternatively, the week containing January 4th).
  • This means that January 1st, 2nd, or 3rd might actually belong to the last week of the previous year.
  • Conversely, the last few days of December might belong to week 1 of the next year.
  • ISO 8601 is widely used because it provides consistency across different countries and cultures, ensures each week belongs to a single year, and is adopted in international business and data exchange.

It’s important to note that in Python, when you use the isocalendar() method (as shown in our examples below), you’re using the ISO 8601 standard. This means that the week numbers you get might not always align with what you might intuitively expect, especially for dates very early or very late in the year. Our post entitled “How to Work with Date and Time in ISO Format in Python” provides some additional color on this subject. 

Now, let’s explore how to work with week numbers in Python through several examples. All of these examples use the ISO 8601 standard via Python’s implementation.

Example 1: Getting the Week Number of a Date

To get the week number of a specific date, we can use the isocalendar() method of a datetime object. This method returns a tuple containing the ISO year, week number, and weekday.

from datetime import datetime

# Create a datetime object
date = datetime(2024, 8, 15)

# Get the ISO calendar representation
iso_calendar = date.isocalendar()

# Extract the week number
week_number = iso_calendar[1]

print(iso_calendar)
print(f"The week number of {date.date()} is {week_number}")

Output:

(2024, 33, 4)
The week number of 2024-08-15 is 33

Example 2: Finding the First Day of a Week

Sometimes, you might need to find the first day (usually Monday) of a given week number. Here’s how you can do that using the ISO 8601 standard:

from datetime import datetime, timedelta

def first_day_of_iso_week(year, week):
    # Create a date object for January 4th of the given year
    # This date is always in the first week of the year according to ISO 8601
    jan4 = datetime(year, 1, 4)
    
    # Get the ISO week number and the weekday of January 4th
    start_iso_week, start_iso_day = jan4.isocalendar()[1:3]
    
    # Calculate the difference in weeks, then adjust for the start of the week
    weeks_diff = week - start_iso_week
    days_to_monday = timedelta(days=(1-start_iso_day))
    
    # Calculate the first day of the given ISO week
    return jan4 + days_to_monday + timedelta(weeks=weeks_diff)

# Example usage
year = 2024
week = 33

first_day = first_day_of_iso_week(year, week)
print(f"The first day of ISO week {week} in {year} is {first_day.date()}")

Output:

The first day of ISO week 33 in 2024 is 2024-08-12

Example 3: Getting the Current Week Number

To get the week number of the current date, we can use the datetime.now() method along with isocalendar(). Remember, this will give us the ISO 8601 week number:

from datetime import datetime

current_date = datetime.now()
current_week = current_date.isocalendar()[1]

print(f"Today's date is {current_date.date()}")
print(f"The current week number is {current_week}")

Output (may vary based on the current date):

Today's date is 2024-08-31
The current week number is 35

Example 4: Calculating the Difference Between Week Numbers

To find the number of weeks between two dates using ISO 8601 week numbers, we can subtract their week numbers:

from datetime import datetime

date1 = datetime(2024, 1, 1)
date2 = datetime(2024, 3, 3)

week1 = date1.isocalendar()[1]
week2 = date2.isocalendar()[1]

week_difference = week2 - week1

print(f"Weeks between {date1.date()} and {date2.date()}: {week_difference}")

Output:

Weeks between 2024-01-01 and 2024-03-03: 8

Example 5: Iterating Through Weeks with Start and End Dates

Finally, let’s look at how to iterate through all the ISO weeks in a year. In this example, we will show the start and end dates of each week. This can be particularly useful for financial reporting or project planning:

from datetime import datetime, timedelta

def iso_year_weeks(year):
    """Yield ISO week number and start/end dates for given year."""
    start_date = datetime(year, 1, 4)
    # Find the first day of the first week
    start_date = start_date - timedelta(days=start_date.weekday())
    
    while start_date.year <= year:
        end_date = start_date + timedelta(days=6)
        iso_year, week_num, _ = start_date.isocalendar()
        
        # Only yield if the week belongs to our target year
        if iso_year == year:
            yield week_num, start_date.date(), end_date.date()
        
        start_date = end_date + timedelta(days=1)

# Example usage
year = 2024
print(f"Weeks in {year}:")
for week_num, start_date, end_date in iso_year_weeks(year):
    print(f"Week {week_num:2d}: {start_date} to {end_date}")

This script will output the week number, start date, and end date for each week in the specified year. Here’s a truncated version of the output:

Weeks in 2024:
Week  1: 2024-01-01 to 2024-01-07
Week  2: 2024-01-08 to 2024-01-14
...
Week 51: 2024-12-16 to 2024-12-22
Week 52: 2024-12-23 to 2024-12-29

By using this function, you can generate a list of all weeks in a year with their corresponding date ranges, which can be extremely useful for various date-based calculations and reporting tasks.

Working with week numbers in Python can be useful for date-based calculations and reporting. By leveraging the datetime module and understanding the ISO 8601 calendar system, you can extract, manipulate, and analyze week-based data in your Python projects. Just remember that the ISO 8601 standard may sometimes give results that differ from other week numbering systems, especially at the beginning and end of the year.

Leave a Reply

Your email address will not be published. Required fields are marked *