Find next date by day of week

datetime, python

Solution

This works:

import datetime as dt

dow={d:i for i,d in 
         enumerate('Mon,Tue,Wed,Thu,Fri,Sat,Sun'.split(','))}

def next_dow(d,day):
    while d.weekday()!=day:
        d+=dt.timedelta(1)

    return d   

d1=min(next_dow(dt.datetime(2013,4,1),day) 
                 for day in (dow['Tue'],dow['Thu']))   
d2=min(next_dow(dt.datetime(2013,4,2),day) 
                 for day in (dow['Mon'],dow['Wed'],dow['Fri'])) 

for d in d1,d2:
    print d.strftime('%Y-%m-%d') 

Or (perhaps better but less general):

def next_dow(d,days):
    while d.weekday() not in days:
        d+=dt.timedelta(1)

    return d   

d1=next_dow(dt.datetime(2013,4,1),(dow['Tue'],dow['Thu']))
d2=next_dow(dt.datetime(2013,4,2),(dow['Mon'],dow['Wed'],dow['Fri']))

for d in d1,d2:
    print d.strftime('%Y-%m-%d') 

Prints:

2013-04-02 
2013-04-03 

Problem

I'm using "datetime" and am having trouble figuring out how to grab the date in the format "%Y-%M-%d" by day of the week. For example: Since today is 2013-04-01 (a Monday), what code would grab the following Tuesday or Thursday? (output should be 2013-04-02 - Tuesday) Or if the date is 2013-04-02, a Tuesday, what code would grab the next Mon, Wed, or Fri? (output should be 2013-04-03 - Next day or Wednesday) Thanks,

Original source

Related problems