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:
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:
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!