我想知道这个:

例如,我有这个日期:

2011-08-10 wednesday

我想知道下个月的第二个星期三:
答案应该是 2011-09-14 wednesday

最佳答案

在评论中解释说 OP 正在寻找一个映射的函数

  • 2011-08-25(第四个星期四)到2011-09-22(第四个星期四)
    下个月)和
  • 2011-08-30(第五个星期二)到2011-09-27(第四个星期二,
    因为九月没有第五个星期二。)


  • 使用 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))
    

    产量
    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
    

    10-08 01:27