Build an array of dates last week, this week and next week

I am constantly stumbling about dates in Python. In my webapp, I want to show every day of the three weeks of the calendar: last week, current week and next week, with Monday indicating the beginning of the week.

The way I am now approaching this is to step back by date until I go on Monday and then calculate another seven days and then add 20 to build a three-week range ... But that seems very awkward.

Does Python have a concept of the week or do I need to manually go around it for days?

Edit: now I am coding it, it is not too terrible, but I am wondering if there is something a little better, again with the concept of weeks, and not 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)] 
+3
source share
3 answers

No, that is pretty much. But understanding the list, based on the result of datetime.date.weekday() , should be fairly simple:

 today = datetime.date(2013, 06, 26) dates = [today + datetime.timedelta(days=i) for i in range(-7 - today.weekday(), 14 - today.weekday())] 

Remember that ranges do not need 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
source

I think a clean and self-documenting solution:

 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
source

The datetime module supports some support for such operations:

 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 
+1
source

Source: https://habr.com/ru/post/957048/


All Articles