好的我试图在Python中获取前一周的日期,假设周从星期日开始,到星期六结束。
通过谷歌和反复试验,我有这个:
def get_week_days(year, week):
d = date(year,1,1)
if(d.weekday()>3):
d = d+timedelta(7-d.weekday())
else:
d = d - timedelta(d.weekday())
dlt = timedelta(days = (week-1)*7)
FH_start = d + dlt
FH_end = d + dlt + timedelta(days=6)
return FH_start, FH_end
print get_week_days(2018, this_week_int)
并且输出:
(datetime.date(2018, 3, 5), datetime.date(2018, 3, 11))
我如何抵消星期日的星期开始,还是有更好的方法来写这个?
答案 0 :(得分:2)
这是一个简单的版本:
from datetime import date, timedelta
def get_week_days(year, week):
year_start = date(year, 1, 1)
# the following line assumes your this_week_int starts at 0
# if this_week_int starts at 1, change to week-2
week_start = year_start + timedelta(days=-year_start.isoweekday(), weeks=week-1)
week_end = week_start + timedelta(days=6)
return week_start, week_end
get_week_days(2018, 1) # (datetime.date(2017, 12, 31), datetime.date(2018, 1, 6)) get_week_days(2018, 10) # (datetime.date(2018, 3, 4), datetime.date(2018, 3, 10))
基本上,.isoweekday()
周一返回1,星期日返回7,所以当你扣除工作日时,会给你星期日的开始。
答案 1 :(得分:0)