[英]Python: Calculating Start Date and End Date of a week from the Week Number & Year From Pandas
I have created the following table with the code我用代码创建了下表
newdf['Year_Date'] = pd.DatetimeIndex(newdf['AbsenceBegDate']).year
newdf['Week_Number'] = pd.DatetimeIndex(newdf['AbsenceBegDate']).week
newdf.drop('AbsenceBegDate', axis=1, inplace=True)
newdf:新的:
Emp_ID Year_Date Week_Number Salary Hours_Worked
5500 2019 30 300 30
3300 2019 31 350 31
3300 2019 32 400 35
I need to add two columns Start Date and End Date of that week from the week number and year我需要从周数和年份中添加该周的两列开始日期和结束日期
For example,例如,
Emp_ID Year_Date Week_Number Salary Hours_Worked Start_Date End_Date
5500 2019 30 300 30 07/25/2019 07/31/2019
3300 2019 31 350 31 08/01/2019 08/07/2019
3300 2019 32 400 35 08/08/2019 08/15/2019
Can you tell me how to extract this start date and end date.你能告诉我如何提取这个开始日期和结束日期吗? your help is appreciated
感谢您的帮助
You could create a function to do this: first define where to start.您可以创建一个函数来执行此操作:首先定义从哪里开始。 Here is for instance what you would do to have today as starting date and you can of course adapt it to your own needs:
例如,以下是您将今天作为开始日期要做的事情,您当然可以根据自己的需要进行调整:
today = date.today()
Week = today.isocalendar()[1]
pastWeek = Week-1
year = 2020
and then define this function:然后定义这个函数:
def get_dates(year, week):
d = date(year,1,1)
if(d.weekday()<= 3):
d = d - timedelta(d.weekday())
else:
d = d + timedelta(7-d.weekday())
dlt = timedelta(days = (week-1)*7)
return d + dlt, d + dlt + timedelta(days=6)
Having done that:这样做之后:
X = get_dates(year, (pastWeek-1) )
which gives you enough info to do the job:这为您提供了足够的信息来完成这项工作:
Startdate = str(X[0])
Enddate = str(X[1])
StartdateNew = pd.to_datetime(Startdate).date()
EnddateNew = pd.to_datetime(Enddate).date()
StartdateNew2 = StartdateNew.strftime('%Y%m%d')
EnddateNew2 = EnddateNew.strftime('%Y%m%d')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.