Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...