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

后端 未结 11 1671
被撕碎了的回忆
被撕碎了的回忆 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: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 ;-)

提交回复
热议问题