0

So I have this function that retrieve the date from given days from today:

def get_date_from_today(d):
    tomorrow = datetime.date.today() + datetime.timedelta(days=d)
    return tomorrow.strftime("%Y/%m/%d")

How do I get for example the date of the next Thursday ?

If today if Thursday I want to get the current date and if not I want to closest Thursday date

falukky
  • 1,099
  • 2
  • 14
  • 34

2 Answers2

2

With .isoweekday() (Monday is 1 and Sunday is 7) you get the weekday as an integer. From there calculate the difference beetween today and the desired weekday. If the difference is 0 the weekday is today. If difference < 0 the neareast is in the past so add 7 to it. Else just add the difference.

def get_date_from_today(d):
    today = datetime.date.today()
    weekday = d-today.isoweekday()
    if weekday == 0:
        return today.strftime("%Y/%m/%d")
    else:
        return (today + datetime.timedelta(days=weekday+7 if weekday < 0 else weekday)).strftime("%Y/%m/%d") 

Note that in this solution your function parameter d is now your desired weekday as an integer.

TimbowSix
  • 342
  • 1
  • 7
0

This code returns the next Thursday:

def get_next_thursday(year, month, day):
weekday = datetime(year, month, day).weekday()
if weekday == 3:
    return datetime(year, month, day)
if weekday > 3:
    return datetime(year, month, day) + timedelta(10 - weekday)
return datetime(year, month, day) + timedelta(3 - weekday)

Driver Code:

print(get_next_thursday(2023, 1, 16))
CNGF
  • 56
  • 4