isocalendar(): Extract ISO Year, Week Number, and Weekday
isocalendar() : to get ISO year, ISO week number, ISO weekday
Today's isocalendar()
from datetime import date
dt=date.today()
print(dt.isocalendar())
Output ( will change based on current date )
(2019, 38, 2)
The date.isocalendar() function returns a tuple with the ISO year, ISO week number, and ISO weekday for a given date. This is especially useful for analyzing data by week or aligning with ISO standards in project timelines.
Using date and time object
from datetime import date
dt=date(2019,12,31)
print(dt.isocalendar())
Output
(2020, 1, 2)
Syntax
date_object.isocalendar()
Example 2: ISO Calendar for a Specific Date
Calculate the ISO week and weekday for a specified date.
from datetime import date
specific_date = date(2022, 12, 31)
print(specific_date.isocalendar())
Iterate over a range of dates and print the ISO week for each.
from datetime import date, timedelta
start_date = date(2024, 12, 25)
for i in range(7):
current_date = start_date + timedelta(days=i)
iso_year, iso_week, iso_weekday = current_date.isocalendar()
print(f"Date: {current_date}, ISO Week: {iso_week}")
Output
Date: 2024-12-25, ISO Week: 52
Date: 2024-12-26, ISO Week: 52
Date: 2024-12-27, ISO Week: 52
Date: 2024-12-28, ISO Week: 52
Date: 2024-12-29, ISO Week: 52
Date: 2024-12-30, ISO Week: 1
Date: 2024-12-31, ISO Week: 1
Example 4: Creating a Week-Based Report
This example demonstrates creating a weekly summary using ISO weeks.
from datetime import date, timedelta
dates = [date(2022, 12, 24), date(2022, 12, 25), date(2023, 1, 1)]
week_summary = {}
for d in dates:
iso_week = d.isocalendar()[1]
week_summary[iso_week] = week_summary.get(iso_week, 0) + 1
print("Weekly summary:", week_summary)
Output:
Weekly summary: {51: 2, 52: 1}
Applications of isocalendar()
Weekly Reports: Track data by ISO week for consistent reporting.
Project Management: Align project milestones with ISO-standard weeks.
Fiscal Year Calculations: Use ISO year and week for fiscal or academic reporting.