Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Number of the Week in a Month

Tags:

python

numbers

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)

like image 830
Francisco Costa Avatar asked Aug 11 '11 16:08

Francisco Costa


People also ask

How many weeks is a Python month?

Number of Weeks in a Month All the months in the calendar have 4 complete weeks because every month has at least 28 days.

How do you count the weeks in a month?

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.

How do I get the week number in Python?

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.


1 Answers

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
like image 181
unutbu Avatar answered Nov 14 '22 00:11

unutbu