python - How to get the Nth occurrence of a day of the week for a given month? -


the week of month not define value. shift between starting week , starting month causes problem in cases.

is there python lib or algorithm calculate value?

you can calculate looping on days of month , counting whether you've come across nth weekday:

import datetime  def get_n_weekday(year, month, day_of_week, n):     count = 0     in xrange(1, 32):         try:             d = datetime.date(year, month, i)         except valueerror:             break         if d.isoweekday() == day_of_week:             count += 1         if count == n:             return d     return none 

for example: get_n_weekday(2016, 1, 1, 1) = first monday of january 2016 datetime.date(2016, 1, 4).

this uses date.isoweekday() means monday 1 , sunday 7.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -