我经常在Python中关注日期。在我的网络应用程序中,我希望每天显示三个星期的日历:上周,当前周和下一周,星期一表示一周的开始。
我目前接近这个的方式是逐步回顾日期,直到我击中星期一,然后再减去7天然后再加20来建立三周的范围...但这感觉真的笨重。
Python有几个星期的概念,还是我必须手动躲避几天?
编辑:现在我把它编码出来,它并不太可怕,但我确实想知道是否有更好的东西,再次用几周的概念而不是几天。
today = datetime.date.today()
last_monday = today - datetime.timedelta(days=today.weekday()) - datetime.timedelta(days=7)
dates = [last_monday + datetime.timedelta(days=i) for i in range(0, 21)]
答案 0 :(得分:3)
不,那就是它。但是,基于datetime.date.weekday()
结果的列表理解应该很容易:
today = datetime.date(2013, 06, 26)
dates = [today + datetime.timedelta(days=i) for i in range(-7 - today.weekday(), 14 - today.weekday())]
请记住,范围不 从0开始: - )
演示:
>>> import datetime
>>> from pprint import pprint
>>> today = datetime.date(2013, 07, 12)
>>> pprint([today + datetime.timedelta(days=i) for i in range(-7 - today.weekday(), 14 - today.weekday())])
[datetime.date(2013, 7, 1),
datetime.date(2013, 7, 2),
datetime.date(2013, 7, 3),
datetime.date(2013, 7, 4),
datetime.date(2013, 7, 5),
datetime.date(2013, 7, 6),
datetime.date(2013, 7, 7),
datetime.date(2013, 7, 8),
datetime.date(2013, 7, 9),
datetime.date(2013, 7, 10),
datetime.date(2013, 7, 11),
datetime.date(2013, 7, 12),
datetime.date(2013, 7, 13),
datetime.date(2013, 7, 14),
datetime.date(2013, 7, 15),
datetime.date(2013, 7, 16),
datetime.date(2013, 7, 17),
datetime.date(2013, 7, 18),
datetime.date(2013, 7, 19),
datetime.date(2013, 7, 20),
datetime.date(2013, 7, 21)]
答案 1 :(得分:3)
我认为干净且自我记录的解决方案是:
import datetime
today = datetime.date.today()
start_day = today - datetime.timedelta(today.weekday() + 7)
three_weeks = [start_day + datetime.timedelta(x) for x in range(21)]
答案 2 :(得分:1)
The datetime
module对此类操作有一些支持:
oneDay = datetime.timedelta(days=1)
oneWeek = datetime.timedelta(days=7)
您可以使用标准数学:
today = datetime.date.today()
lastMonday = today - datetime.timedelta(days=today.weekday())
lastWeek = lastMoney - oneWeek
nextWeek = lastMoney + oneWeek