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?
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)