我用代码创建了下表
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
我需要从星期数和年份中添加两列“开始日期”和“该周的结束日期”
例如,
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
您能告诉我如何提取此开始日期和结束日期。感谢您的帮助
答案 0 :(得分:0)
您可以创建一个函数来执行此操作: 首先定义从哪里开始。例如,这是您今天要作为开始日期执行的操作,当然您可以根据自己的需要进行调整:
today = date.today()
Week = today.isocalendar()[1]
pastWeek = Week-1
year = 2020
,然后定义此功能:
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)
已经做到了:
X = get_dates(year, (pastWeek-1) )
为您提供足够的信息来完成这项工作:
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')