Ron
Ron

Reputation: 23466

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().

Upvotes: 9

Views: 11957

Answers (2)

Dj Mamana
Dj Mamana

Reputation: 384

This other version found here is flawless and simple: https://www.pythonprogramming.in/how-to-get-start-and-end-of-week-data-from-a-given-date.html

##
# Python's program to get start and end of week

from datetime import datetime, timedelta

date_str = '2018-01-14'
date_obj = datetime.strptime(date_str, '%Y-%m-%d')

start_of_week = date_obj - timedelta(days=date_obj.weekday())  # Monday
end_of_week = start_of_week + timedelta(days=6)  # Sunday
print(start_of_week)
print(end_of_week)

Upvotes: 5

Ron
Ron

Reputation: 23466

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.

Upvotes: 13

Related Questions