如何在python中获取当月的上周四或周三日期



我有一个数据帧,其中有日期。我想从nf_date列中获取每个日期,如果nf_date列中不存在上周四日期,则获取该月的上周四,然后获取上周三日期(which is previous of last Thursday) of that month.在获取上周四或周三日期后,我想将该日期附加到新列名expiry中的当前数据帧中,我的代码粘贴在此链接中

您可以通过从月底日期返回来获得特定的工作日:

import pandas as pd
# a dummy example
df = pd.DataFrame({'date': ['2021-10-29', '2021-11-01', '2021-12-16']})
#       month last Thursday: 2021-10-28,   2021-11-25,   2021-12-30
# we have a datetime series in our dataframe...
df['date'] = pd.to_datetime(df['date'])
# we can easily get the month's end date:
df['mEnd'] = df['date'] + pd.tseries.offsets.MonthEnd(1)
# Thursday is weekday 3, so the offset for given weekday is
offset = (df['mEnd'].dt.weekday - 3) % 7
# now to get the date of the last Thursday of the month, subtract it from 
# month end date:
df['last_Thrs'] = df['mEnd'] - pd.to_timedelta(offset, unit='D')
print(df)
#         date       mEnd  last_Thrs
# 0 2021-10-29 2021-10-31 2021-10-28
# 1 2021-11-01 2021-11-30 2021-11-25
# 2 2021-12-16 2021-12-31 2021-12-30

最新更新