0

I am trying to create a program that will take today's date and find the most recent historical beginning and end of the week (excluding bank holidays and weekends). The idea being is that it will take today's date "02/26/23" and return 02/21/23 for the beginning (02/20/23 was a bank holiday) and 02/24/23 for the end of the week.

My current code is

import pandas as pd
import datetime as dt
from pandas.tseries.holiday import USFederalHolidayCalendar

end = dt.datetime.now()
start = dt.datetime(end.year, end.month, end.day-5)

dr = pd.date_range(start=start, end=end)
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start=dr.min(), end=dr.max())
A = dr[~dr.isin(holidays)]
B = A[A.weekday != 5]
B = B[B.weekday != 6]

for year in set(B.year):
    tmp = B[B.year == year]
    for week in set(tmp.week):
        temp = tmp[tmp.week == week]
        print(temp[temp.weekday == temp.weekday.min()])  # begining of week
        print(temp[temp.weekday == temp.weekday.max()])  # ending of week

This results in:

DatetimeIndex(['2023-02-21'], dtype='datetime64[ns]', freq=None)
DatetimeIndex(['2023-02-24'], dtype='datetime64[ns]', freq=None)

But also gives a "FutureWarning: weekofyear and week have been deprecated ..."

Is there any way to get this in the datetime format so if I printed it, it would say 2023-02-21 for example. How can I avoid the FutureWarning?

(BTW I had sourced some of this from https://stackoverflow.com/a/43674721/21292653

La Myass
  • 29
  • 6

1 Answers1

0

Instead of tmp.week, you should try pd.Index(tmp.isocalendar().week) that is:

import pandas as pd
import datetime as dt
from pandas.tseries.holiday import USFederalHolidayCalendar

end = dt.datetime.now()
start = dt.datetime(end.year, end.month, end.day-5)

dr = pd.date_range(start=start, end=end)
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start=dr.min(), end=dr.max())
A = dr[~dr.isin(holidays)]
B = A[A.weekday != 5]
B = B[B.weekday != 6]

for year in set(B.year):
    tmp = B[B.year == year]
    for week in set(pd.Index(tmp.isocalendar().week)):
        temp = tmp[pd.Index(tmp.isocalendar().week) == week]
        print(temp[temp.weekday == temp.weekday.min()])  # begining of week
        print(temp[temp.weekday == temp.weekday.max()])  # ending of week
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40