Search code examples
pythontimeweek-number

Week number of the month?


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


Solution

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