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

后端 未结 11 1623
被撕碎了的回忆
被撕碎了的回忆 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:21
    weekday = 0 ## Monday
    dt = datetime.datetime.now().replace(hour=0, minute=0, second=0) ## or any specific date
    days_remaining = (weekday - dt.weekday() - 1) % 7 + 1
    next_dt = dt + datetime.timedelta(days_remaining)
    
    0 讨论(0)
  • 2020-11-27 16:23

    This is example of calculations within ring mod 7.

    import datetime
    
    
    def next_day(given_date, weekday):
        day_shift = (weekday - given_date.weekday()) % 7
        return given_date + datetime.timedelta(days=day_shift)
    
    now = datetime.date(2018, 4, 15) # sunday
    names = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',    
             'saturday', 'sunday']
    for weekday in range(7):
        print(names[weekday], next_day(now, weekday))
    

    will print:

    monday 2018-04-16
    tuesday 2018-04-17
    wednesday 2018-04-18
    thursday 2018-04-19
    friday 2018-04-20
    saturday 2018-04-21
    sunday 2018-04-15
    

    As you see it's correctly give you next monday, tuesday, wednesday, thursday friday and saturday. And it also understood that 2018-04-15 is a sunday and returned current sunday instead of next one.

    I'm sure you'll find this answer extremely helpful after 7 years ;-)

    0 讨论(0)
  • 2020-11-27 16:24

    via list comprehension?

    from datetime import *
    [datetime.today()+timedelta(days=x) for x in range(0,7) if (datetime.today()+timedelta(days=x)).weekday() % 7 == 0]
    
    (0 at the end is for next monday, returns current date when run on monday)
    
    0 讨论(0)
  • 2020-11-27 16:28
    import datetime
    def next_weekday(d, weekday):
        days_ahead = weekday - d.weekday()
        if days_ahead <= 0: # Target day already happened this week
            days_ahead += 7
        return d + datetime.timedelta(days_ahead)
    
    d = datetime.date(2011, 7, 2)
    next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
    print(next_monday)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-27 16:32

    Another alternative uses rrule

    from dateutil.rrule import rrule, WEEKLY, MO
    from datetime import date
    
    next_monday = rrule(freq=WEEKLY, dtstart=date.today(), byweekday=MO, count=1)[0]
    

    rrule docs: https://dateutil.readthedocs.io/en/stable/rrule.html

    0 讨论(0)
提交回复
热议问题