如何找到一周的开始和开始(Python)

f45qwnt8  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(103)

我正在尝试创建一个程序,它将获取今天的日期,并查找最近的历史开始和结束的一周(不包括银行假日和周末)。想法是,它将获取今天的日期"02/26/23",并返回02/21/23作为开始(02/20/23是银行假日)和02/24/23作为结束。
我当前的代码是

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

这导致:

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

但也会给出"未来警告:weekofyear和week已被弃用..."
有没有办法把它转换成日期时间格式,这样如果我打印它,它会显示为2023 - 02 - 21。我怎样才能避免FutureWarning?
(BTW我从https://stackoverflow.com/a/43674721/21292653中获得了其中一些

xxhby3vn

xxhby3vn1#

您应该尝试pd.Index(tmp.isocalendar().week),而不是tmp.week,它是:

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

相关问题