How to find out what week number is current year on June 16th (wk24) with Python?
The easiest way to get the week number is to use the Python datetime isocalendar() function. The isocalendar() function returns a tuple object with three components: year, week and weekday.
Get week number from date using strftime() function.
In Python, it can be easily done with the help of pandas. Example 2: We can also do the same for multiple dates by adding more dates in the 'Date' object. Example 3: Extracting week number from dates for multiple dates using date_range() and to_series().
datetime.date
has a isocalendar()
method, which returns a tuple containing the calendar week:
>>> import datetime >>> datetime.date(2010, 6, 16).isocalendar()[1] 24
datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.
In Python 3.9+ isocalendar()
returns a namedtuple with the fields year
, week
and weekday
which means you can access the week explicitly using a named attribute:
>>> import datetime >>> datetime.date(2010, 6, 16).isocalendar().week 24
You can get the week number directly from datetime as string.
>>> import datetime >>> datetime.date(2010, 6, 16).strftime("%V") '24'
Also you can get different "types" of the week number of the year changing the strftime
parameter for:
%U
- Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53
%W
- Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53[...]
(Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the
strftime()
method.[...]
%V
- ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53from: datetime — Basic date and time types — Python 3.7.3 documentation
I've found out about it from here. It worked for me in Python 2.7.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With