Jos*_*osh 29
为了使用直接分割,需要根据当月第一天的位置(在一周内)调整您所查看日期的月份日期.因此,如果您的月份恰好在星期一(一周的第一天)开始,您可以按照上面的建议进行划分.但是,如果月份从星期三开始,您将要添加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))
Run Code Online (Sandbox Code Playgroud)
小智 14
查看包装Pendulum
>>> dt = pendulum.parse('2018-09-30')
>>> dt.week_of_month
5
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 10
如果您的第一周从该月的第一天开始,您可以使用整数除法:
import datetime day_of_month = datetime.datetime.now().day week_number = (day_of_month - 1) // 7 + 1
小智 9
我知道这已经有好几年了,但我花了很多时间试图找到这个答案.我做了自己的方法,并认为我应该分享.
日历模块具有monthcalendar方法,该方法返回2D数组,其中每行代表一周.例如:
import calendar
calendar.monthcalendar(2015,9)
Run Code Online (Sandbox Code Playgroud)
结果:
[[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]]
Run Code Online (Sandbox Code Playgroud)
numpy在这里你的朋友在哪里.而且我在美国所以我希望这个星期在周日开始,第一周标记为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)
Run Code Online (Sandbox Code Playgroud)
回报
3
Run Code Online (Sandbox Code Playgroud)
这个版本可以改进,但作为 python 模块(日期时间和日历)的第一眼,我做了这个解决方案,我希望可能有用:
from datetime import datetime
n = datetime.now()
#from django.utils.timezone import now
#n = now() #if you use django with timezone
from calendar import Calendar
cal = Calendar() # week starts Monday
#cal = Calendar(6) # week stars Sunday
weeks = cal.monthdayscalendar(n.year, n.month)
for x in range(len(weeks)):
if n.day in weeks[x]:
print x+1
Run Code Online (Sandbox Code Playgroud)
乔希的答案必须稍作调整,以适应第一天是周日。
def get_week_of_month(date):
first_day = date.replace(day=1)
day_of_month = date.day
if(first_day.weekday() == 6):
adjusted_dom = (1 + first_day.weekday()) / 7
else:
adjusted_dom = day_of_month + first_day.weekday()
return int(ceil(adjusted_dom/7.0))
Run Code Online (Sandbox Code Playgroud)
def week_of_month(date_value):
week = date_value.isocalendar()[1] - date_value.replace(day=1).isocalendar()[1] + 1
return date_value.isocalendar()[1] if week < 0 else week
Run Code Online (Sandbox Code Playgroud)
date_value 应采用时间戳格式 这将在所有情况下给出完美的答案。它纯粹基于 ISO 日历