杰瑞科技汇

Python中weekofyear函数如何正确使用?

Of course! In Python, getting the week number of a year is a common task. The best way to do this depends on whether you're using Python 3.9+ or an older version, and which week-numbering system you need (ISO vs. US).

Python中weekofyear函数如何正确使用?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the simplest method to more advanced options.

The Short Answer (Python 3.9+)

If you are using Python 3.9 or newer, the datetime module has a built-in isocalendar() method that makes this incredibly easy.

from datetime import date
# Create a date object
my_date = date(2025, 10, 26)
# Get the ISO week number
iso_week_number = my_date.isocalendar().week
print(f"The date is: {my_date}")
print(f"The ISO week number is: {iso_week_number}")

Output:

The date is: 2025-10-26
The ISO week number is: 43

Detailed Explanation: Methods and Systems

There are two primary systems for numbering weeks:

Python中weekofyear函数如何正确使用?-图2
(图片来源网络,侵删)
  1. ISO Week Date: This is the international standard (ISO 8601).

    • Week 1 is the week that contains the first Thursday of the year.
    • This means it can have 52 or 53 weeks.
    • It's the most common standard for business and international data exchange.
  2. US Week Numbering (or "Week of the Year"):

    • Week 1 is the week that contains January 1st.
    • This means the first week of the year can have as few as 1 day (if Jan 1 is a Saturday or Sunday).
    • It's used in some US-specific applications but is less common internationally.

Let's look at how to get both.


Method 1: Using datetime.isocalendar() (Recommended)

This is the best method for getting the ISO week number. It works on Python 3.7+ but is more idiomatic and efficient in Python 3.9+.

Python中weekofyear函数如何正确使用?-图3
(图片来源网络,侵删)

How it works:

The isocalendar() method returns a named tuple with three values: (ISO year, ISO week number, ISO weekday).

from datetime import date
d1 = date(2025, 1, 1) # A Sunday
d2 = date(2025, 1, 2) # A Monday
d3 = date(2025, 1, 1) # A Monday
d4 = date(2025, 12, 31) # A Tuesday
# For d1, Jan 1st is a Sunday. According to ISO rules, this is in the last week
# of the *previous* year (2025-W52-7).
iso_week_1 = d1.isocalendar().week
iso_week_2 = d2.isocalendar().week
iso_week_3 = d3.isocalendar().week
iso_week_4 = d4.isocalendar().week
print(f"Date: {d1} -> ISO Week: {iso_week_1}") # Week 52 of 2025
print(f"Date: {d2} -> ISO Week: {iso_week_2}") # Week 1 of 2025
print(f"Date: {d3} -> ISO Week: {iso_week_3}") # Week 1 of 2025
print(f"Date: {d4} -> ISO Week: {iso_week_4}") # Week 53 of 2025 (a leap year)

Output:

Date: 2025-01-01 -> ISO Week: 52
Date: 2025-01-02 -> ISO Week: 1
Date: 2025-01-01 -> ISO Week: 1
Date: 2025-12-31 -> ISO Week: 53

Method 2: Using datetime.strftime() for US Week Numbering

If you need the US week number (where week 1 starts on Jan 1), you can use the strftime() method with the format code %U.

How it works:

  • %U: Week number of the year (Sunday as the first day of the week). Days before the first Sunday of the year are in week 0.
from datetime import date
d1 = date(2025, 1, 1) # A Sunday
d2 = date(2025, 1, 2) # A Monday
us_week_1 = d1.strftime("%U")
us_week_2 = d2.strftime("%U")
print(f"Date: {d1} -> US Week (starts Sunday): {us_week_1}")
print(f"Date: {d2} -> US Week (starts Sunday): {us_week_2}")

Output:

Date: 2025-01-01 -> US Week (starts Sunday): 00
Date: 2025-01-02 -> US Week (starts Sunday): 01

Important Note on %U: If your week starts on Monday instead of Sunday, use %W instead. The behavior is the same, but Monday is considered the first day of the week.


Method 3: Using the calendar Module

The calendar module is another great option, especially if you're working with week-related tasks frequently.

How it works:

  • calendar.weekday(year, month, day): Returns the day of the week (0=Monday, 6=Sunday).
  • calendar.isocalendar(year, month, day): Returns a tuple (ISO year, ISO week, ISO weekday). This is the same as date(...).isocalendar().
  • calendar.timegm(...): Can be used to build your own week calculation if needed.

Example: Getting the ISO week number with calendar

import calendar
from datetime import date
# Using the calendar.isocalendar function
d = date(2025, 10, 26)
iso_week_from_calendar = calendar.isocalendar(d.year, d.month, d.day)[1]
print(f"Date: {d}")
print(f"ISO Week (from calendar module): {iso_week_from_calendar}")

Output:

Date: 2025-10-26
ISO Week (from calendar module): 43

Summary: Which Method to Use?

Your Goal Recommended Method Python Version Notes
Get ISO Week Number my_date.isocalendar().week 7+ Best practice. Standard, clear, and efficient.
Get US Week Number (Week starts Sunday) my_date.strftime("%U") All versions Common in the US, but less standard internationally.
Get US Week Number (Week starts Monday) my_date.strftime("%W") All versions A slight variation of the US standard.
Need to find week number for a string date? datetime.strptime() + isocalendar() All versions You must first parse the string into a date or datetime object.

Complete Example: Handling a String Date

Often, you'll have a date as a string (e.g., from a file or user input). You must first parse it into a datetime object.

from datetime import datetime
# A date string
date_string = "2025-03-15"
# 1. Parse the string into a datetime object
#    The format "%Y-%m-%d" matches "Year-Month-Day"
dt_object = datetime.strptime(date_string, "%Y-%m-%d")
# 2. Get the ISO week number using the recommended method
iso_week = dt_object.isocalendar().week
# 3. Get the US week number (starting on Sunday)
us_week = dt_object.strftime("%U")
print(f"Original String: {date_string}")
print(f"Parsed Datetime: {dt_object}")
print(f"ISO Week Number: {iso_week}")
print(f"US Week Number (starts Sunday): {us_week}")

Output:

Original String: 2025-03-15
Parsed Datetime: 2025-03-15 00:00:00
ISO Week Number: 11
US Week Number (starts Sunday): 11
分享:
扫描分享到社交APP
上一篇
下一篇