user15590480
user15590480

Reputation: 97

Python Get date from weekday of current week?

I'm trying to get date from weekday of current week

week_day = date.today().weekday() 

From this week_day I'm trying to get exact day of week - 27/05/2021

Upvotes: 0

Views: 2019

Answers (1)

aveuiller
aveuiller

Reputation: 1551

If I understand correctly, you want to fetch a date of the current week's weekday by number (or name, but you can easily make the transition).

I can propose you the following function, computing the difference with the current date:

from datetime import date, timedelta
def date_for_weekday(day: int):
     today = date.today()
     # weekday returns the offsets 0-6
     # If you need 1-7, use isoweekday
     weekday = today.weekday()
     return today + timedelta(days=day - weekday)

# Usage
>>> date_for_weekday(0)
datetime.date(2021, 5, 24)
>>> date_for_weekday(1)
datetime.date(2021, 5, 25)
>>> date_for_weekday(4)
datetime.date(2021, 5, 28)
>>> date_for_weekday(3)
datetime.date(2021, 5, 27)

Upvotes: 5

Related Questions