pythondatetimependulum

What week of the month is it?


pendulum v2.1.0 on macOS

>>> import pendulum
>>> d = pendulum.Date(2019, 12, 31)
>>> d.week_of_month
-46

Isn't new years day 2019 the week 5 of the month?

How to interpret week of the month result negative 46?


Solution

  • You can use calendar:

    import calendar
    import numpy as np
    calendar.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(2019,12,31)
    

    Output:

    5
    

    This is what they use:

    def week_of_month(d):
        first_day_of_month = d.replace(day=1)
        print(d.week_of_year,first_day_of_month.week_of_year)
    
        return d.week_of_year - first_day_of_month.week_of_year + 1
    
    week_of_month(d)
    

    Bug is here

    first_day_of_month.week_of_year gives --> 48
    

    Earlier they were using this:

    import math
    def week_of_month(d):
            return int(math.ceil(d.day / 7))
    

    which gives correct output