从给定的工作日和月份计算日期,但年份可变(例如 "x" 年八月的第三个星期日)

Calculate date from given weekday and month, but variable year (e.g. 3rd Sunday in August in "x" year)

我的 pandas 数据框 "MSYs" 有一个 "start_yr" 从日期时间列构建的变量 "Start Date" 显示某人开始日期的年份(注意 [=月和日 "Start Date" 也各不相同)。

start_yr = pd.DatetimeIndex(MSYs['Start Date']).year

我想使用 start_yr 来帮助我 return 另一列中的日期时间日期 "Grant Start" 显示该可变年份八月的第三个星期日。我被难住了。

这是对类似问题的回答,可能会对您有所帮助。

使用日期时间库。

遍历当年 8 月的子集。

检查是否是星期四。

Python: third Friday of a month

这是一个基于该线程中的一个答案的解决方案。这是一个通用的解决方案,因此您应该能够选择一个月、星期几和您想要的月份中的数字并获得该日期。

注意:工作日从星期一开始索引为 0。所以星期天的索引是 6,星期一的索引是 0。所以当你将 day_of_week 输入这个函数时,确保你选择 0 到 6 之间的数字。

我已经默认选择给定年份的月份的第三个星期日

import datetime as dt

def get_year_day(year,month=8,day_of_week=6,num_in_month=3):
    ## set up possible ranges
    range_1 = 7*(num_in_month-1)+1
    range_2 = 7*num_in_month+1
    ## loop through possible range in the year and the month
    for i in range(range_1,range_2):
        date = dt.datetime(year=year,month=month, day=i)
        ## if we have our weekday we can break
        if date.weekday()==day_of_week:
            break
    return date

for i in range(2015,2021):

    print(i,get_year_day(i))

2015 2015-08-16 00:00:00
2016 2016-08-21 00:00:00
2017 2017-08-20 00:00:00
2018 2018-08-19 00:00:00
2019 2019-08-18 00:00:00
2020 2020-08-16 00:00:00