Skip to content

Instantly share code, notes, and snippets.

@ratpik
Last active December 18, 2015 14:39
Show Gist options
  • Save ratpik/5798390 to your computer and use it in GitHub Desktop.
Save ratpik/5798390 to your computer and use it in GitHub Desktop.
Get days in the same week as given date in python
from datetime import timedelta
#Input date is a datetime instance
"""
>>> get_days_in_week(datetime(2013,06,17))
[datetime.datetime(2013, 6, 17, 0, 0), datetime.datetime(2013, 6, 18, 0, 0), datetime.datetime(2013, 6, 19, 0, 0), datetime.datetime(2013, 6, 20, 0, 0), datetime.datet ime(2013, 6, 21, 0, 0), datetime.datetime(2013, 6, 22, 0, 0), datetime.datetime(2013, 6, 23, 0, 0)]
>>> get_days_in_week(datetime(2013,06,17))
[datetime.datetime(2013, 6, 17, 0, 0), datetime.datetime(2013, 6, 18, 0, 0), datetime.datetime(2013, 6, 19, 0, 0), datetime.datetime(2013, 6, 20, 0, 0), datetime.datet ime(2013, 6, 21, 0, 0), datetime.datetime(2013, 6, 22, 0, 0), datetime.datetime(2013, 6, 23, 0, 0)]
"""
def get_days_in_week(date):
today = date.date().weekday()
prev = [r-today for r in range(0, today)]
next = [r-today for r in range(today, 7)]
return [date + timedelta(days=d) for d in prev + next]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment