3

I have seen many ways to determine week of the year. Like by giving instruction datetime.date(2016, 2, 14).isocalendar()[1] I get 6 as output. Which means 14th feb 2016 falls under 6th Week of the year. But I couldn't find any way by which I could find week of the Month.

Means IF I give input as some_function(2016,2,16) I should get output as 3, denoting me that 16th Feb 2016 is 3rd week of the Feb 2016

[ this is different question than similar available question, here I'm asking about finding week no of the month and not of the year]

Point Networks
  • 1,071
  • 1
  • 13
  • 35

2 Answers2

0

This function did the work what I wanted

from math import ceil

def week_of_month(dt):

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))

I got this function from This StackOverFlow Answer

Community
  • 1
  • 1
Point Networks
  • 1,071
  • 1
  • 13
  • 35
0
import datetime
def week_number_of_month(date_value):
    week_number = (date_value.isocalendar()[1] - date_value.replace(day=1).isocalendar()[1] + 1)
    if week_number == -46:
        week_number = 6
   return week_number
        
date_given = datetime.datetime(year=2018, month=12, day=31).date()
        
week_number_of_month(date_given)
kamran kausar
  • 4,117
  • 1
  • 23
  • 17