1

Basically what i want is to have the day of the week's date after saying next week or similar format and i though i found what i need in here:

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

However testing the code proved it's giving somewhat answers i'd want differently :

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(2017, 11, 30)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
print(next_monday)

It worked as expected to give the date correctly for next_weekday(d,0), 1,2,3 then for next_weekday(d,4) i get 2017-12-01 which my system interprets as faulty because this friday equate 2017-12-01 while next friday equates 2017-12-08 same for saturday and Sunday, so basically what i want if the day of the week we're seeking is still in the same week to give the date of that day for the week after.

Sarah
  • 53
  • 4

1 Answers1

0

Could you not just always add 7 to days_ahead rather than only when the "Target day has already happend this week" to get a day in next week every time:

import datetime

def next_weekday(d, weekday):
  days_ahead = weekday - d.weekday() + 7
  return d + datetime.timedelta(days_ahead)

d = datetime.date(2017, 11, 30)
next_friday = next_weekday(d, 4)
print(next_friday) # 2017-12-08 which is next week rather than the friday this week: 2017-12-01
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • 1
    My bad, works just fine for this example, i'll test it for a couple of test cases and accept it if it works, thanks. – Sarah Nov 30 '17 at 08:19