我怎样才能在Python中获得前一周的成绩?

时间:2013-10-30 15:22:47

标签: python python-2.7 python-datetime

我目前正在从星期一开始到周日结束,但我怎样才能从周一开始到周日结束?以下是我本周的情况:

>>> 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

1 个答案:

答案 0 :(得分:17)

只需将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)