week commencing Saturday in Panda

I have different dates in my data. I want to make the date as a week commencing Saturday.How to do it?

enter image description here

Answer

My understanding of your question based on the image is: given a date, generate a date where:

  1. if the initial date is a Saturday, the generated date is the same date and
  2. if the initial date is not Saturday, the generated date is the most recent Saturday before that date

The datetime.dayofweek() method returns 0..6 for Monday..Sunday.

import datetime

def most_recent_saturday(d):
    day_adjustment = (dt.weekday() + 2) % 7
    delta = datetime.timedelta(days=day_adjustment)
    return dt - delta

for day in range(4, 11):
    dt = datetime.datetime(2021, 3, day)
    dt2 = most_recent_saturday(dt)

    print("date: {}, day of week {}, saturday: {}".format(dt, dt.weekday(), dt2))

Edit: Since OP wanted to use pandas dataframe, this would work (modifying the example given in comment):

import datetime
import pandas as pd

vals = []
for day in range(4, 11):
    dt = datetime.datetime(2021, 3, day)
    vals.append(dt)

df = pd.DataFrame(data=vals, columns=['SYS_DATE'])
df['Week Commencing Saturday'] = pd.to_datetime(df['SYS_DATE']) - pd.offsets.Week(weekday=4) + pd.offsets.Day(1)

print(df)

Output:

    SYS_DATE Week Commencing Saturday
0 2021-03-04               2021-02-27
1 2021-03-05               2021-02-27
2 2021-03-06               2021-03-06
3 2021-03-07               2021-03-06
4 2021-03-08               2021-03-06
5 2021-03-09               2021-03-06
6 2021-03-10               2021-03-06

Leave a Reply

Your email address will not be published. Required fields are marked *