python - Week number of the month

后端 未结 14 1433
忘掉有多难
忘掉有多难 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:28

    Josh' answer seems the best but I think that we should take into account the fact that a week belongs to a month only if its Thursday falls into that month. At least that's what the iso says.

    According to that standard, a month can have up to 5 weeks. A day could belong to a month, but the week it belongs to may not.

    I have taken into account that just by adding a simple

    if (first_day.weekday()>3) :
            return ret_val-1
        else:
            return ret_val
    

    where ret_val is exactly Josh's calculated value. Tested on June 2017 (has 5 weeks) and on September 2017. Passing '2017-09-01' returns 0 because that day belongs to a week that does not belong to September.

    The most correct way would be to have the method return both the week number and the month name the input day belongs to.

提交回复
热议问题