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

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

    Here's a succinct and generic alternative to the slightly weighty answers above.

    # Returns the date of the next given weekday after
    # the given date. For example, the date of next Monday.
    # NB: if it IS the day we're looking for, this returns 0.
    # consider then doing onDay(foo, day + 1).
    onDay = lambda date, day: date + datetime.timedelta(days=(day-date.weekday()+7)%7)
    

提交回复
热议问题