twinklenugget
twinklenugget

Reputation: 98

Reverse of datetime.weekday()?

d : Datetime object

Given a date d and a day of the week x in the range of 0–6, return the date of x within the same week as d.

I can think of some ways to do this, but they all seem rather inefficient. Is there a pythonic way?

Example

Input: datetime(2020,2,4,18,0,55,00000), 6

Output: date(2020,2,7)


Input: datetime(2020,2,4,18,0,55,00000), 0

Output date(2020,2,3)

Upvotes: 1

Views: 556

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169424

This approach gets the first day in the week and goes from there to find the date requested by the weekday integer:

import datetime as dt 

def weekday_in_week(d,weekday=None): 
    if not weekday: 
        return None 
    week_start = d - dt.timedelta(days=d.weekday()) 
    return week_start + dt.timedelta(days=weekday) 

Example usage:

In [27]: weekday_in_week(dt.date.today(),6)                                     
Out[27]: datetime.date(2020, 2, 9)

Remember that the weekdays are as such: 0 is Monday, 6 is Sunday.

Upvotes: 2

Related Questions