How to get all datetime instances of the current week, given the day?

During the day, I want to get all the days (datetime instances) of the week that day.

I have a solution, please correct me if something is wrong, if there is a more efficient method.

>>> import datetime >>> today = datetime.datetime(2013, 06, 26) >>> today datetime.datetime(2013, 6, 26, 0, 0) >>> day_of_week = today.isocalendar()[2] - 1 >>> day_of_week 2 >>> start_date = today - timedelta(days=day_of_week) >>> start_date datetime.datetime(2013, 6, 24, 0, 0) # Got monday >>> dates = [start + timedelta(days=i) for i in range(7)] >>> dates [datetime.datetime(2013, 6, 24, 0, 0), datetime.datetime(2013, 6, 25, 0, 0), datetime.datetime(2013, 6, 26, 0, 0), datetime.datetime(2013, 6, 27, 0, 0), datetime.datetime(2013, 6, 28, 0, 0), datetime.datetime(2013, 6, 29, 0, 0), datetime.datetime(2013, 6, 30, 0, 0)] 

I want Monday to have a start date and a Sunday end date.

+4
source share
1 answer

Instead, I would use datetime.date() to make it clear that we are calculating the dates here, and use date.weekday() to get the current business day instead of using the .isocalendar() call, .isocalendar() us the day of the week to 0 (0 - Monday).

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

Demo:

 >>> from pprint import pprint >>> import datetime >>> today = datetime.date(2013, 06, 26) >>> pprint([today + datetime.timedelta(days=i) for i in range(0 - today.weekday(), 7 - today.weekday())]) [datetime.date(2013, 6, 24), datetime.date(2013, 6, 25), datetime.date(2013, 6, 26), datetime.date(2013, 6, 27), datetime.date(2013, 6, 28), datetime.date(2013, 6, 29), datetime.date(2013, 6, 30)] 

On python 2, you can replace range() with xrange() if you want; for a 7-day value that will not matter much.

Just to make it explicit; datetime.weekday() exists and .isoweekday() , so there is no need to use .isocalendar() anywhere.

+11
source

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


All Articles