Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Know the second wednesday of the next month with a given date

I would like to know this:

I have for example this date:

2011-08-10 wednesday

and i would like to know the next second wednesday of the next month: The answer should be 2011-09-14 wednesday.

like image 671
Tiago Moutinho Avatar asked Dec 22 '22 10:12

Tiago Moutinho


1 Answers

In the comments it was explained that the OP is looking for a function which maps

  1. 2011-08-25 (the fourth Thursday) to 2011-09-22 (the fourth Thursday of the next month) and
  2. 2011-08-30 (the fifth Tuesday) to 2011-09-27 (the fourth Tuesday, because there is no fifth Tuesday in September.)

Using dateutil:

import datetime
import dateutil.relativedelta as relativedelta

def next_month(date):
    weekday=relativedelta.weekday(date.isoweekday()-1)   
    weeknum=(date.day-1)//7+1
    weeknum=weeknum if weeknum<=4 else 4
    next_date=date+relativedelta.relativedelta(
        months=1,day=1,weekday=weekday(weeknum))
    return next_date

start=datetime.date(2011,8,1)
for i in range(31):
    date=start+datetime.timedelta(days=i)
    next_date=next_month(date)    
    print('{d} --> {n}'.format(d=date,n=next_date))

yields

2011-08-01 --> 2011-09-05
2011-08-02 --> 2011-09-06
2011-08-03 --> 2011-09-07
2011-08-04 --> 2011-09-01
2011-08-05 --> 2011-09-02
2011-08-06 --> 2011-09-03
2011-08-07 --> 2011-09-04
2011-08-08 --> 2011-09-12
2011-08-09 --> 2011-09-13
2011-08-10 --> 2011-09-14
2011-08-11 --> 2011-09-08
2011-08-12 --> 2011-09-09
2011-08-13 --> 2011-09-10
2011-08-14 --> 2011-09-11
2011-08-15 --> 2011-09-19
2011-08-16 --> 2011-09-20
2011-08-17 --> 2011-09-21
2011-08-18 --> 2011-09-15
2011-08-19 --> 2011-09-16
2011-08-20 --> 2011-09-17
2011-08-21 --> 2011-09-18
2011-08-22 --> 2011-09-26
2011-08-23 --> 2011-09-27
2011-08-24 --> 2011-09-28
2011-08-25 --> 2011-09-22 # Oddly non-monotonic, but correct according to specifications
2011-08-26 --> 2011-09-23
2011-08-27 --> 2011-09-24
2011-08-28 --> 2011-09-25
2011-08-29 --> 2011-09-26 # 5th Monday maps to 4th Monday since there is no 5th Monday in September
2011-08-30 --> 2011-09-27
2011-08-31 --> 2011-09-28
like image 111
unutbu Avatar answered Dec 24 '22 02:12

unutbu