在Python中获取给定周数的第一天和最后一天 [英] 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).
在1月1日不是星期一的几周中出现了困难,因此我无法使用标准的 datetime.datetime.strptime()
。
There is a difficulty for weeks where Jan 1st is not a Monday so I cannot use the standard datetime.datetime.strptime()
.
推荐答案
这里是解决方案:
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)
我扩展了这篇文章的伟大逻辑。
更新
第一个日历周存在陷阱。某些国家/地区对第一周的处理方式有所不同。例如,在德国,如果一月份的第一周少于4天,则将其计为上一年的最后一周。在维基百科中有一个概述。
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.
这篇关于在Python中获取给定周数的第一天和最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!