How to get week number in Python? How to get week number in Python? python python

How to get week number in Python?


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().week24


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, …, 53

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


I believe date.isocalendar() is going to be the answer. This article explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the datetime page of the Python documentation.

>>> dt = datetime.date(2010, 6, 16) >>> wk = dt.isocalendar()[1]24

.isocalendar() return a 3-tuple with (year, wk num, wk day). dt.isocalendar()[0] returns the year,dt.isocalendar()[1] returns the week number, dt.isocalendar()[2] returns the week day. Simple as can be.