我正在尝试获取日期列表的星期结束日期。我找到了以下代码,它适用于传统的周一至周日,但我需要一个周日至周六(周日为第一天)。
from datetime import datetime, timedelta
date_str = '2019-06-16'
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
start_of_week = date_obj - timedelta(days=date_obj.weekday())
end_of_week = start_of_week + timedelta(days=6)
print(start_of_week)
print(end_of_week)
上面的代码返回:
2019-06-10 00:00:00
2019-06-16 00:00:00
我需要它来返回此值:
2019-06-16 00:00:00
2019-06-22 00:00:00
答案 0 :(得分:0)
因此,工作日星期一返回0,星期日返回6。要将星期日更改为0,将星期六更改为6,请
start_of_week = date_obj - timedelta((date_obj.weekday() + 1) % 7)
答案 1 :(得分:0)
我认为在python中,星期日是一周的开始日期,哈哈。下面的代码可能会帮助您。
from datetime import datetime, timedelta
# this may be the func you need.
def date_start_end(date):
"""
calc the start and end date for input date. Sunday is the start day for a week.
:param date: any date
:return: st: the start date(Sunday) for this week
:return: end: the end date(Saturday) for this week
"""
weekDate = int(date.strftime('%w'))
st = date + timedelta(-weekDate)
end = date + timedelta(6 - weekDate)
return st, end
date = datetime(2019, 6, 16)
st, end = date_start_end(date)
print(st)
print(end)
>>>2019-06-16 00:00:00
>>>2019-06-22 00:00:00
答案 2 :(得分:0)
加上我的两分钱。 Datetime还具有一个>>> re.sub(r"(?<=[A-Z]).", "", text)
'LLC, SA, LP'
>>>
方法,该方法的星期一为1,星期日为7。类似于@Deepstop的回答,但更短:
isoweekday