Search code examples
python-3.xdatecalendardayofweek

Get last day of week of a given date


Given any day of the year, such as today, I would have the last day of the current week.

For example, current day is 2021-12-27 (Monday), so the last day of this week is 2022-01-01 (Saturday), because of isoWeek in my systems starts from Sundays.

from datetime import datetime
dt = datetime.now()

print(dt) # 2021-12-27 12:57:57.004108

last_day_of_week = get_ldow(dt)
print(last_day_of_week) # 2022-01-01 00:00:00.000000

How get_ldow(df) could be implemented?


Solution

  • Import of datatime can be tricky.

    import datetime
    
    dt = datetime.datetime.today() # 2021-12-27 13:40:10.204296
    
    def get_ldow(dt_input):
        return dt_input + datetime.timedelta(days=(6 - dt_input.isoweekday() % 7))
    
    last_day_of_week = get_ldow(dt)
    
    print(last_day_of_week) # 2022-01-01 13:40:10.204296