【问题标题】:How to get last Thursday date or Wednesday date of current month in python如何在python中获取当前月份的上周四日期或周三日期
【发布时间】:2022-01-19 09:00:29
【问题描述】:

我有一个数据框,其中有日期。我想从nf_date 列中获取每个日期,如果nf_date 列中不存在上周四日期,则获取该月的上周四当前数据框中的日期在新列名expirymy code is pasted in this link

【问题讨论】:

    标签: python-3.x pandas dataframe datetime timedelta


    【解决方案1】:

    您可以从当月的结束日期返回获取具体的工作日:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2023-02-08
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      相关资源
      最近更新 更多