现在是一个月中的第几周?

What week of the month is it?

macOS 上的 pendulum v2.1.0

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

2019 年元旦不是第 5 周吗?

如何解释当月第几周结果为负数 46?

您可以使用日历:

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)

输出:

5

这是他们使用的:

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)

错误在这里

first_day_of_month.week_of_year gives --> 48

早些时候他们使用这个:

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

给出正确的输出