Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get week number in Python?

Tags:

python

How to find out what week number is current year on June 16th (wk24) with Python?

like image 975
Gerry Avatar asked Apr 08 '10 14:04

Gerry


People also ask

How do I get week number in 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.

How do I get the week number from a date column in Python?

Get week number from date using strftime() function.

How do I convert a date to a week number in Python?

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


2 Answers

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 
like image 71
Horst Gutmann Avatar answered Oct 04 '22 04:10

Horst Gutmann


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

like image 32
jotacor Avatar answered Oct 04 '22 03:10

jotacor