Home >Backend Development >Python Tutorial >How to Get the Week Number for a Specific Date in Python?
Retrieving Week Number in Python
Obtaining the current week number for a given date is a common task in programming. In Python, several methods can be employed to accomplish this.
datetime.date.isocalendar() Method
The datetime.date object provides the isocalendar() method, which returns a tuple containing the year, week number, and weekday for the specified date. To find the week number for a particular date, simply invoke the isocalendar() method on the corresponding datetime.date object.
For instance, to determine the week number for June 16th of the current year:
<code class="python">import datetime date_obj = datetime.date(2023, 6, 16) week_number = date_obj.isocalendar()[1] print(week_number) # Output: 24</code>
In Python 3.9 and above, isocalendar() returns a namedtuple with fields for year, week, and weekday, allowing you to access the week number directly:
<code class="python">import datetime date_obj = datetime.date(2023, 6, 16) week_number = date_obj.isocalendar().week print(week_number) # Output: 24</code>
Other Methods
Alternatively, there are third-party libraries like dateutil that provide additional methods for manipulating date and time:
<code class="python">from dateutil.relativedelta import relativedelta date_obj = datetime.date(2023, 6, 16) week_number = date_obj + relativedelta(weekday=relativedelta.MO(-1)) print(week_number.isocalendar()[1]) # Output: 24</code>
By utilizing these methods, you can easily retrieve the week number for any given date in Python.
The above is the detailed content of How to Get the Week Number for a Specific Date in Python?. For more information, please follow other related articles on the PHP Chinese website!