For my python dataframe, I want another column to be created which will have the last sunday for the current week of the date when the code is run. Week starts from Sunday. For ex my dataframe looks like :
ID Process
1 Manual
2 Semi
3 Automatic
Now say, I have run the code today which is: 8/27/2021. Last Sunday for the current week according to today's date is 08/22/2021. so my dataframe will look like :
ID Process Last Sunday
1 Manual 08/22/2021
2 Semi 08/22/2021
3 Automatic 08/22/2021
Last Sunday will change every time based on the date I run the code on. However, if I am running the code on the Sunday , it should give me the date of that Sunday since my week starts from Sunday.
CodePudding user response:
Deriving from get the last sunday and saturday's date in python, you can do:
from datetime import datetime, timedelta
df['Last Sunday'] = (datetime.now()
-timedelta(days=((datetime.now().isoweekday() 1) % 7))
).strftime('%m/%d/%Y')
CodePudding user response:
Try using pd.to_datetime
with pd.Timedelta
>>> df['Last Sunday'] = (pd.to_datetime('now') - pd.Timedelta(days=((pd.to_datetime('now').dayofweek - 1) % 7))).date()
>>> df
ID Process Last Sunday
0 1 Manual 2021-08-24
1 2 Semi 2021-08-24
2 3 Automatic 2021-08-24
>>>