Home > Software design >  Change datetime weekday without going back in time
Change datetime weekday without going back in time

Time:02-18

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

CodePudding user response:

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)

CodePudding user response:

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))
  • Related