Home > database >  To get sunday's and saturday's date from a dataframe which has dates from Monday to tuesda
To get sunday's and saturday's date from a dataframe which has dates from Monday to tuesda

Time:08-06

I have below dataframe

    0
0   2022-07-25
1   2022-07-26
2   2022-07-27
3   2022-07-28
4   2022-07-29

this is from monday to tuesday . I need to add previous sunday date that is 2022-07-24 and saturday day 2022-07-23 into dataframe by calculating monday -1 and monday -2 likewise. please help

CodePudding user response:

You can pd.DateTime module to get the previous weekend date for each date in your column.

Creating the data

df = pd.DataFrame({'Date': ['2022-07-25','2022-07-26','2022-07-27','2022-07-28','2022-07-29']})
df['Date'] = pd.to_datetime(df['Date'])

Calculate saturday and sunday dates

sat, sun = 5, 6
# Day of week for saturday : 5
df['Saturday_prev'] = df['Date'] - pd.to_timedelta((df['Date'].dt.dayofweek - sat)%7, unit='d')
# Day of week for Sunday : 6
df['Sunday_prev'] = df['Date'] - pd.to_timedelta((df['Date'].dt.dayofweek - sun)%7, unit='d')

Output :

This gives us the expected output :

        Date Saturday_prev Sunday_prev
0 2022-07-25    2022-07-23  2022-07-24
1 2022-07-26    2022-07-23  2022-07-24
2 2022-07-27    2022-07-23  2022-07-24
3 2022-07-28    2022-07-23  2022-07-24
4 2022-07-29    2022-07-23  2022-07-24

For a variety of dates, the program gives you expected output

df = pd.DataFrame({'Date': ['2022-08-05','2022-08-10','2022-08-12','2022-08-21','2022-08-26']})

Output :

        Date Saturday_prev Sunday_prev
0 2022-08-05    2022-07-30  2022-07-31
1 2022-08-10    2022-08-06  2022-08-07
2 2022-08-12    2022-08-06  2022-08-07
3 2022-08-21    2022-08-20  2022-08-21
4 2022-08-26    2022-08-20  2022-08-21

CodePudding user response:

Himanshuman's answer is great, but I just wanted to show that using a dataframe for this problem really isn't necessary:

def get_saturday(input_date):
    date = pd.to_datetime(input_date)
    days_ago = (date.day_of_week - 5)%7
    return (date - pd.to_timedelta(days_ago, unit='d')).date()

user_input = '2022-07-28'
print(get_saturday(user_input))

# Output:
2022-07-23
  • Related