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

后端 未结 11 1624
被撕碎了的回忆
被撕碎了的回忆 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)
    
    0 讨论(0)
  • 2020-11-27 16:34

    Try

    >>> dt = datetime(2011, 7, 2)
    >>> dt + timedelta(days=(7 - dt.weekday()))
    datetime.datetime(2011, 7, 4, 0, 0)
    

    using, that the next monday is 7 days after the a monday, 6 days after a tuesday, and so on, and also using, that Python's datetime type reports monday as 0, ..., sunday as 6.

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

    You can start adding one day to date object and stop when it's monday.

    >>> d = datetime.date(2011, 7, 2)
    >>> while d.weekday() != 0: #0 for monday
    ...     d += datetime.timedelta(days=1)
    ... 
    >>> d
    datetime.date(2011, 7, 4)
    
    0 讨论(0)
  • 2020-11-27 16:36
    import datetime
    
    d = datetime.date(2011, 7, 2)
    while d.weekday() != 0:
        d += datetime.timedelta(1)
    
    0 讨论(0)
  • 2020-11-27 16:39

    This will give the first next Monday after given date:

    import datetime
    
    def get_next_monday(year, month, day):
        date0 = datetime.date(year, month, day)
        next_monday = date0 + datetime.timedelta(7 - date0.weekday() or 7)
        return next_monday
    
    print get_next_monday(2011, 7, 2)
    print get_next_monday(2015, 8, 31)
    print get_next_monday(2015, 9, 1)
    

    2011-07-04
    2015-09-07
    2015-09-07

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