python - Week number of the month

后端 未结 14 1432
忘掉有多难
忘掉有多难 2020-12-01 08:11

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

14条回答
  •  隐瞒了意图╮
    2020-12-01 08:44

    A variation on @Manuel Solorzano's answer:

    from calendar import monthcalendar
    def get_week_of_month(year, month, day):
        return next(
            (
                week_number
                for week_number, days_of_week in enumerate(monthcalendar(year, month), start=1)
                if day in days_of_week
            ),
            None,
        )
    

    E.g.:

    >>> get_week_of_month(2020, 9, 1)
    1
    >>> get_week_of_month(2020, 9, 30)
    5
    >>> get_week_of_month(2020, 5, 35)
    None
    

提交回复
热议问题