Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given a day, I want to get all days(datetime instances) of the week in which day is present.

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

>>> 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 be start date and sunday the end date.

like image 388
rajpy Avatar asked Jun 24 '13 13:06

rajpy


1 Answers

I'd use datetime.date() instead to make it clear we are calculating dates here, and use date.weekday() to get the current weekday instead of using the .isocalendar() call, giving us a 0-based weekday number (0 is 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 like; for a 7-day value that won't make much difference.

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

like image 200
Martijn Pieters Avatar answered Nov 15 '22 15:11

Martijn Pieters