Home >Backend Development >Python Tutorial >How to Determine the Week Number of a Specific Date in Python?

How to Determine the Week Number of a Specific Date in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 02:20:03184browse

How to Determine the Week Number of a Specific Date in Python?

Determining Week Number in Python

Finding the current week number of the year can be a useful task in various programming applications. Python provides a convenient method to achieve this using the datetime module.

Problem:

How do you determine the week number of the current year on a specific date, such as June 16th (wk24)?

Solution:

The datetime.date object offers an isocalendar() method that returns a tuple containing the calendar week information:

<code class="python">import datetime

date_obj = datetime.date(2010, 6, 16)
week_number = date_obj.isocalendar()[1]

print(week_number)  # Output: 24</code>

The isocalendar() method returns a tuple of three values: (year, week_number, weekday_number). The second element of the tuple represents the week number of the year.

In Python 3.9 and above, isocalendar() returns a namedtuple with explicit fields: year, week, and weekday. This allows you to access the week number using attribute notation:

<code class="python">import datetime

date_obj = datetime.date(2010, 6, 16)
week_number = date_obj.isocalendar().week

print(week_number)  # Output: 24</code>

The above is the detailed content of How to Determine the Week Number of a Specific Date in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn