views:

701

answers:

5

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

+11  A: 

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week:

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

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday for the given date instance.

Horst Gutmann
Apples to oranges. You've got 6-26-2010. He's looking for 6-16-2010.
Byron Sommardahl
@Byron: now, that's pathetic.
SilentGhost
It would help if you explained the '`[1]`', or gave a pointer where to look for the information.
Jonathan Leffler
Updated (also with the date requested by the OP)
Horst Gutmann
@SilentGhost: Come on! The difference in example dates was throwing people off. I think its important to use the asker's examples so that simple things don't get overlooked.
Byron Sommardahl
+2  A: 

Look at datetime.datetime.isocalendar.

miles82
+3  A: 

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.

Byron Sommardahl
+1 for the link which explains the non-intuitive nature of ISO weeks.
Mark Ransom
+6  A: 

Here's another option:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime("%U", d))

which prints 24.

See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

Bart Kiers
+1 for the URL to more information
Jonathan Leffler
A: 

The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year.

If you'd rather use a definition that says week 1 is always January 1 through January 7 regardless of the day of the week, here it is.

>>> testdate=datetime.datetime(2010,6,16)
>>> print ((testdate - datetime.datetime(testdate.year,1,1)).days / 7) + 1
24
Mark Ransom