问题
I'm constantly tripping over things with regards to dates in Python. In my webapp I want to show every day of three weeks of a calendar: The last week, the current week and the following week, with Monday denoting the beginning of a week.
The way I would currently approach this is stepping back through dates until I hit Monday and then subtract a further seven days and then add 20 to build the three-week range... But this feels really clunky.
Does Python's have a concept of weeks or do I have to manually bodge it around with days?
Edit: Now I code it out, it's not too horrific but I do wonder if there's not something slightly better, again with a concept of weeks rather than just days.
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)]
回答1:
Nope, that's pretty much it. But a list comprehension, basing off the datetime.date.weekday() result, should be easy enough:
today = datetime.date(2013, 06, 26)
dates = [today + datetime.timedelta(days=i) for i in range(-7 - today.weekday(), 14 - today.weekday())]
Remember, ranges do not have to start at 0. :-)
Demo:
>>> 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)]
回答2:
I guess clean and self documenting solution is:
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)]
回答3:
The datetime module has some support for operations like this:
oneDay = datetime.timedelta(days=1)
oneWeek = datetime.timedelta(days=7)
You can use standard math with them:
today = datetime.date.today()
lastMonday = today - datetime.timedelta(days=today.weekday())
lastWeek = lastMoney - oneWeek
nextWeek = lastMoney + oneWeek
来源:https://stackoverflow.com/questions/17611774/build-array-of-dates-in-last-week-this-week-and-next-week