'Change datetime weekday without going back in time

How do I set the weekday for the provided datetime object without looping back in time?

This is how I first did it

now = dt.datetime.now() # February 18
target_weekday = 2 # Wednesday next week
future = ((now - dt.timedelta(days=now.weekday())) + dt.timedelta(days=target_weekday))

This outputs this week's wednesday which is February 16 (In the past) What I want is for it to output next week's wednesday, not all the time though, it only has to move to next week if the provided target_weekday is in the past. But if the weekday is let's say 5, then it would just add an extra day



Solution 1:[1]

It can be checked if the target weekday is in the past or future and add days according to that in timedelta

now = dt.datetime.now()
target_weekday = 5
result = now + dt.timedelta(
  days=(7 - target_weekday if now.weekday() > target_weekday else target_weekday - now.weekday()))
print(result)

Solution 2:[2]

So I was able to figure out a solution that works all the time

def construct_next(weekday: int, datetime: dt.datetime) -> dt.datetime:
    if weekday == datetime.weekday():
        return datetime + dt.timedelta(days=7)
    elif weekday > datetime.weekday():
        return datetime + dt.timedelta(days=weekday - datetime.weekday())
    return ((datetime - dt.timedelta(days=datetime.weekday())) + dt.timedelta(days=weekday + 7))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aditya
Solution 2 Matthew Dev