When specifying a date:
datetime.datetime(2011, 8, 15)
How can i get to know that this is the third week of the month?
What if I want this dates?
datetime.datetime(2011, 2, 28) //should return 4
datetime.datetime(2011, 8, 29) //should return 5
I understand that only February has 4 weeks if the given date is in a leap year (bissextile)
Number of Weeks in a Month All the months in the calendar have 4 complete weeks because every month has at least 28 days.
With a simple mathematical calculation, you can calculate how many weeks are in each month. Count the number of days in the month and divide that number by 7, which is the number of days in one week. For example, if March has 31 days, there would be a total of 4.43 weeks in the month.
YOu can use the isocalender function from the datetime module to get the current week. Create the object of the date first, then call isocalender() on this object. This returns a 3-tuple of Year, Week number and Day of Week.
In [115]: d = datetime.datetime(2011, 2, 28)
In [116]: (d.day-1)//7+1
Out[116]: 4
In [117]: d = datetime.datetime(2011, 8, 29)
In [118]: (d.day-1)//7+1
Out[118]: 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With