[Django]-How to get the date by day name in python?

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

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)

Leave a comment