Find the date for the first Monday after a given a date

后端 未结 11 1691
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 15:47

Given a particular date, say 2011-07-02, how can I find the date of the next Monday (or any weekday day for that matter) after that date?

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:30

    Another simple elegant solution is to use pandas offsets.
    I find it very helpful and robust when playing with dates.
    - If you want the first Sunday just modify the frequency to freq='W-SUN'.
    - If you want a couple of next Sundays, change the offsets.Day(days).
    - Using pandas offsets allow you to ignore holidays, work only with Business Days and more.
    You can also apply this method easily on a whole DataFrame using apply method.

    # Getting the closest monday from a given date
    closest_monday = pd.date_range(start=date, end=date + offsets.Day(6), freq='W-MON')[0]
    
    # Adding a 'ClosestMonday' column with the closest monday for each row in a pandas df using apply
    # Require you to have a 'Date' column in your df
    def get_closest_monday(row):
        return pd.date_range(start=row.Date, end=row.Date + offsets.Day(6), freq='W-MON')[0]
    
    df['ClosestMonday'] = df.apply(lambda row: get_closest_monday(row), axis=1)
    

提交回复
热议问题