3

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,

dawg
  • 98,345
  • 23
  • 131
  • 206
Delos Chang
  • 1,823
  • 3
  • 27
  • 47

2 Answers2

4

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 
dawg
  • 98,345
  • 23
  • 131
  • 206
0

You could try something like this:

from datetime import datetime
from datetime import timedelta

def return_next_tues_thur(dt):
    while True:
        dt += timedelta(days=1)
        dow = dt.strftime(%w)
        if dow == 2 || dow == 4:
           return dt

dt = datetime.now()  # Or you set it: dt = datetime(2013, 4, 1)
next_tues_thur = return_next_tues_thur(dt)
print next_tues_thur.strftime("%Y-%m-%d")

This uses the strftime method and the %w modifier to get the day-of-week from a datetime object. (%w will return an int in the range 0 to 6 where zero is Sunday.)

This idea should be easily extensible to Monday/Wednesday/Friday.

john_science
  • 6,325
  • 6
  • 43
  • 60