python是否提供了一种轻松获取当月的当前周 (1:4)的方法?
发布于 2013-05-29 10:30:31
为了使用直除法,您要查看的日期的月份日期需要根据该月第一天的位置(在一周内)进行调整。因此,如果你的月份恰好从星期一(一周的第一天)开始,你可以像上面建议的那样做除法。但是,如果该月从星期三开始,则需要添加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))
发布于 2015-09-16 03:27:57
我知道这是很久以前的事了,但我花了很多时间试图找到这个答案。我制定了自己的方法,并认为我应该分享。
calendar模块有一个monthcalendar方法,它返回一个2D数组,其中每一行表示一个星期。例如:
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]]
你的朋友在哪呢。我在美国,所以我希望这一周从周日开始,第一周的标签是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
发布于 2018-11-16 18:50:49
查看包Pendulum
>>> dt = pendulum.parse('2018-09-30')
>>> dt.week_of_month
5
https://stackoverflow.com/questions/3806473
复制相似问题