Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...