How to find out what week number is this year on June 16th (wk24) with Python?
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.
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.
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
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