Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the date for the first Monday after a given date

Tags:

python

date

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?

like image 931
ghickman Avatar asked Jul 02 '11 17:07

ghickman


3 Answers

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)
like image 74
phihag Avatar answered Oct 23 '22 01:10

phihag


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

def onDay(date, day):
    """
    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).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
like image 20
user1034533 Avatar answered Oct 23 '22 01:10

user1034533


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.

like image 27
Dirk Avatar answered Oct 23 '22 03:10

Dirk