我当前的当前周是从星期一开始,到星期日结束,但是如何才能获得前一周从星期一开始,直到星期日结束?这是本周我现在所拥有的:

>>> import datetime
>>> today = datetime.date.today()
>>> weekday = today.weekday()
>>> start_delta = datetime.timedelta(days=weekday)
>>> start_of_week = today - start_delta
>>> week_dates = []
>>> for day in range(7):
...     week_dates.append(start_of_week + datetime.timedelta(days=day))
...
>>> week_dates
[datetime.date(2013, 10, 28), datetime.date(2013, 10, 29), datetime.date(2013, 10, 30),     datetime.date(2013, 10, 31), datetime.date(2013, 11, 1), datetime.date(2013, 11, 2), datetime.date(2013, 11, 3)]
>>> week_dates[0], week_dates[-1]
(datetime.date(2013, 10, 28), datetime.date(2013, 11, 3)) <--- Monday, Sunday

最佳答案

只需在您的weeks=1中添加start_delta,即可减去一周的时间:

>>> start_delta = datetime.timedelta(days=weekday, weeks=1)

因此,对于今天(2013年10月30日,星期三),start_delta将为9天(返回至2013年10月21日,上一个星期一)。
>>> start_delta
datetime.timedelta(9)
>>> start_of_week = today - start_delta
>>> start_of_week
datetime.date(2013, 10, 21)

关于python - 如何获得Python的前一周?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19686856/

10-15 12:39