Reputation: 582
I am trying to get the weeks of the current month. I can get the number of the week in that month(current_w) but I will need to get a list in the correct order. For example, for July, it will be w = [27, 28, 29, 30]
because current week is in the third order of the 4 weeks of this month. Can somebody help me on that?
import datetime
kw = datetime.datetime.today().isocalendar()[1]
weeks = [7,14,21,28]
for idx, i in enumerate(weeks):
delta = datetime.timedelta(days=i)
if (a - delta).month != a.month:
current_w = idx
Upvotes: 2
Views: 2108
Reputation: 148880
If you only want weeks that are fully included in a month, the first week will be the one that contains the 7th of that month. And the last week will one before the one that contains the 1st of next month.
That is enough to give the following function:
def weeks_in_month(month, year=None):
"""Returns the (ISO) weeks fully contained in a month.
month is an integer between 1 and 12. Year is the current year
if not given"""
if year is None:
year = datetime.date.today().year
first = datetime.date(year, month, 7).isocalendar()[1]
nextd = datetime.date(year + 1, 1, 1) if month == 12 \
else datetime.date(year, month + 1, 1)
nextw = nextd.isocalendar()[1]
return list(range(first, nextw))
Upvotes: 1
Reputation: 1273
You could use datetime
to get both the first and the last week and then just everything in between.
import datetime
import calendar
year = datetime.datetime.now().year
month = datetime.datetime.now().month
first_week = datetime.datetime(year, month, calendar.monthrange(year, month)[0]).isocalendar()[1]
last_week = datetime.datetime(year, month, calendar.monthrange(year, month)[1]).isocalendar()[1]
print(list(range(first_week, last_week + 1)))
from datetime import datetime
would save you all the datetime.datetime
usage btw.
Upvotes: 4