python - Week number of the month

Joao Figueiredo picture Joao Figueiredo · Sep 27, 2010 · Viewed 45.3k times · Source

Does python offer a way to easily get the current week of the month (1:4) ?

Answer

Josh picture Josh · May 29, 2013

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 ceil

def 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))