3

I have a day name such as Monday. and the current day is Wednesday. Now i want to get the date of next coming Monday. How can i do it with a best practice in a very short way. right now i am trying to do this with bunch of if conditions and it made things messy and very difficult.

here is my code :

day_time = timezone.now()
current_day = day_time.strftime("%A")
coming_day = "monday"
if coming_day == current_day:
    day_time  = day_time

if coming_day=="sunday" and coming_day == "monday":
    day_time  = day_time + timedelta(days=6)

if coming_day=="sunday" and coming_day == "tuesday":
    day_time  = day_time + timedelta(days=5)

if coming_day=="sunday" and coming_day == "wednesday":
    day_time  = day_time + timedelta(days=4)

if coming_day=="sunday" and coming_day == "thursday":
    day_time  = day_time + timedelta(days=3)

.........so on
Ahmed Yasin
  • 185
  • 8
  • I don't see a bunch of if conditions, only one. And your code doesn't do what you want to do. It just checks if the current_day equals the coming_day and then adds 7 days to day_time – Sembei Norimaki Nov 10 '22 at 16:30
  • 1
    Oh i didn't posted all code , let me update quesion – Ahmed Yasin Nov 10 '22 at 16:32
  • 2
    `if coming_day=="sunday" and coming_day == "monday"` can never be true. You are checking `coming_day` twice. – timgeb Nov 10 '22 at 16:47

2 Answers2

2

We can add a day to the current day till the new day_time has same day as the required day -

day_time = timezone.now()
coming_day = "monday"
while day_time.strftime("%A") != coming_day:
    day_time = day_time + timedelta(days=1)
Jay
  • 2,431
  • 1
  • 10
  • 21
0

You might want to check out dateutils. It will do the math for you. Your only task will then be to convert your day strings into the right calendar.<DAY> value.

In [1]: import datetime

In [2]: import calendar

In [3]: import dateutil.relativedelta

In [4]: now = datetime.datetime.now()

In [5]: now + dateutil.relativedelta.relativedelta(weekday=calendar.MONDAY)
Out[5]: datetime.datetime(2022, 11, 14, 11, 46, 19, 184918)