Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first and last day of given week number in python

I need a function which returns the first and last day respectively the Monday and Sunday of a given week number (and a year).

There is a difficulty for weeks where Jan 1st is not a Monday so I cannot use the standard datetime.datetime.strptime().

like image 571
Ron Avatar asked Dec 24 '22 06:12

Ron


1 Answers

Here's the solution:

import calendar
import datetime
from datetime import timedelta

def get_start_and_end_date_from_calendar_week(year, calendar_week):       
    monday = datetime.datetime.strptime(f'{year}-{calendar_week}-1', "%Y-%W-%w").date()
    return monday, monday + datetime.timedelta(days=6.9)

I extended the great logic of this post.

Update

There is a pitfall with the first calendar week. Certain countries handle the first week number differently. For example in Germany, if the first week in January has less than 4 days, it is counted as the last week of the year before. There's an overview at Wikipedia.

like image 127
Ron Avatar answered Dec 25 '22 18:12

Ron