pythondatetimeweekday

How do I get the next X day of the week


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


Solution

  • 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.