简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM