[英]Calculate date from given weekday and month, but variable year (e.g. 3rd Sunday in August in "x" year)
My pandas dataframe "MSYs" has a "start_yr" variable built from a datetime column "Start Date" showing the year of someone's start date (note that month and day of "Start Date" also vary).我的 pandas 数据框“MSYs”有一个“start_yr”变量,它是从日期时间列“开始日期”构建的,显示某人开始日期的年份(请注意,“开始日期”的月份和日期也有所不同)。
start_yr = pd.DatetimeIndex(MSYs['Start Date']).year
I want to use start_yr to help me return a datetime date in another column "Grant Start" showing the third Sunday in August of that variable year.我想使用 start_yr 来帮助我在另一列“Grant Start”中返回日期时间日期,该列显示该可变年份八月的第三个星期日。 I am stumped.我很难过。
This is an answer to a similar quesion which might help you.这是对类似问题的回答,可能会对您有所帮助。
Use the datetime library.使用日期时间库。
Loop through subset of days in august of that year.遍历当年 8 月的几天子集。
Check if if it is thursday.检查是否是星期四。
Python: third Friday of a month Python:一个月的第三个星期五
Here is a solution based on one of the answers in that thread.这是一个基于该线程中的答案之一的解决方案。 It is a generalized solution so you should be able to pick a month, a day of the week and the number in the month you want and get that date.这是一个通用的解决方案,因此您应该能够选择一个月、星期几和您想要的月份中的数字并获得该日期。
Note: Week days are 0 indexed starting at Monday.注意:工作日从星期一开始为 0 索引。 So Sunday's index is 6 and monday's index is 0. So when you feed the day_of_week into this function make sure you choose numbers between 0 and 6.所以星期天的索引是 6,星期一的索引是 0。所以当你将 day_of_week 提供给这个函数时,确保你选择 0 到 6 之间的数字。
I have defaulted it to choose the 3rd Sunday of the month given the year.我已经默认它选择给定年份的月份的第三个星期日。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.