月份的周数?
Python有没有简单的方法来获取当前是这个月的第几周(1到4周)?
23 个回答
18
如果你的一周是从这个月的第一天开始的,你可以使用整数除法:
import datetime day_of_month = datetime.datetime.now().day week_number = (day_of_month - 1) // 7 + 1
28
我知道这个问题已经有很多年了,但我花了很多时间才找到答案。我自己写了一个方法,觉得应该分享一下。
日历模块有一个叫做 monthcalendar 的方法,它会返回一个二维数组,每一行代表一周。例如:
import calendar
calendar.monthcalendar(2015,9)
结果是:
[[0,0,1,2,3,4,5],
[6,7,8,9,10,11,12],
[13,14,15,16,17,18,19],
[20,21,22,23,24,25,26],
[27,28,29,30,0,0,0]]
在这里,numpy 的 where 方法非常有用。而且我在美国,所以我希望一周从星期天开始,第一周标记为 1:
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(2015,9,14)
返回的结果是
3
58
为了使用简单的除法,你需要根据这个日期所在月份的第一天在一周中的位置来调整日期。如果这个月的第一天是星期一(也就是一周的第一天),那么你可以直接按照上面提到的方法进行除法运算。可是,如果这个月的第一天是星期三,你就需要先加上2,然后再进行除法。这些内容都包含在下面的函数中。
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))