Does python offer a way to easily get the current week of the month (1:4) ?
In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the month starts on a Wednesday, you'll want to add 2 and then do the division. This is all encapsulated in the function below.
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))
def week_of_month(date_value):
return (date_value.isocalendar()[1] - date_value.replace(day=1).isocalendar()[1] + 1)
date_value should in timestamp format This will give the perfect answer in all the cases
Move to last day of week in month and divide to 7
from math import ceil
def week_of_month(dt):
""" Returns the week of the month for the specified date.
"""
# weekday from monday == 0 ---> sunday == 6
last_day_of_week_of_month = dt.day + (7 - (1 + dt.weekday()))
return int(ceil(last_day_of_week_of_month/7.0))
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
I found a quite simple way:
import datetime
def week(year, month, day):
first_week_month = datetime.datetime(year, month, 1).isocalendar()[1]
if month == 1 and first_week_month > 10:
first_week_month = 0
user_date = datetime.datetime(year, month, day).isocalendar()[1]
if month == 1 and user_date > 10:
user_date = 0
return user_date - first_week_month
returns 0 if first week
This version could be improved but as a first look in python modules (datetime and calendar), I make this solution, I hope could be useful:
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