Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Week number of the month

Does python offer a way to easily get the current week of the month (1:4) ?

like image 884
Joao Figueiredo Avatar asked Sep 27 '10 17:09

Joao Figueiredo


People also ask

How many weeks is a Python month?

A few months have some extra days, but they are not counted as a week because these extra days are not enough, to sum up to 7 days (1 week = 7 days). Hence, it can be said that on average, 1 month = 4 weeks and 2 days, or 1 month = 413 4 1 3 weeks.

How do I get the week number in Python?

Another way you can get the week number from a date variable in Python is with the strftime() function. The strftime() function allows you to format dates with different date formats. You can pass “%W”, “%U”, or “%V” to strftime() to get the number of the week according to three different calendars.


1 Answers

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)) 
like image 186
Josh Avatar answered Sep 18 '22 22:09

Josh