python - Week number of the month python - Week number of the month python python

python - Week number of the month


In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the month starts on a Wednesday, you'll want to add 2 and then do the division. This is all encapsulated in the function below.

from math import ceildef week_of_month(dt):    """ Returns the week of the month for the specified date.    """    first_day = dt.replace(day=1)    dom = dt.day    adjusted_dom = dom + first_day.weekday()    return int(ceil(adjusted_dom/7.0))


I know this is years old, but I spent a lot of time trying to find this answer. I made my own method and thought I should share.

The calendar module has a monthcalendar method that returns a 2D array where each row represents a week. For example:

import calendarcalendar.monthcalendar(2015,9)

result:

[[0,0,1,2,3,4,5], [6,7,8,9,10,11,12], [13,14,15,16,17,18,19], [20,21,22,23,24,25,26], [27,28,29,30,0,0,0]]

So numpy's where is your friend here. And I'm in USA so I want the week to start on Sunday and the first week to be labelled 1:

import calendarimport numpy as npcalendar.setfirstweekday(6)def get_week_of_month(year, month, day):    x = np.array(calendar.monthcalendar(year, month))    week_of_month = np.where(x==day)[0][0] + 1    return(week_of_month)get_week_of_month(2015,9,14)

returns

3


If your first week starts on the first day of the month you can use integer division:

import datetimeday_of_month = datetime.datetime.now().dayweek_number = (day_of_month - 1) // 7 + 1