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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 07:05:30597browse

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

Determining the Week Number in Python

Finding out the week number of a specific date, such as June 16th (week 24), can be achieved with Python's datetime module.

SOLUTION:

The datetime.date class provides an instance method called isocalendar(). When invoked on a specified date, it returns a tuple containing the following information:

  • Year
  • Week number
  • Weekday

EXAMPLE:

To obtain the week number for June 16th, execute the following code:

<code class="python">>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24</code>

This will output 24, indicating that June 16th belongs to the 24th week of the year.

PYTHON 3.9 ENHANCEMENT:

In Python 3.9 and higher, isocalendar() returns a namedtuple with specific fields:

  • year
  • week
  • weekday

This allows for more convenient access to the week number:

<code class="python">>>> import datetime
>>> iso = datetime.date(2010, 6, 16).isocalendar()
>>> iso.week
24</code>

The above is the detailed content of How to Determine the Week Number of a 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