Skip to content

Instantly share code, notes, and snippets.

@arkanister
Last active October 12, 2018 14:04
Show Gist options
  • Save arkanister/9455735e944ee1cc77892ba688c42b68 to your computer and use it in GitHub Desktop.
Save arkanister/9455735e944ee1cc77892ba688c42b68 to your computer and use it in GitHub Desktop.
How to get the first and last day of a week based on a date.
# coding: utf-8
"""
Sometimes we really need to get the first and the last date
on a week, this function will help you to get this whatever
day your week starts.
"""
import datetime
MO, TU, WE, TH, FR, SA, SU = range(1, 8)
def week_range(dt, week_start=SU):
"""
Find the first/last day of the week for the given day.
Returns a tuple of ``(start_date, end_date)``.
"""
# isocalendar calculates the year, week of the year, and day of the week.
# dow is Mon = 1, ... Sat = 6, Sun = 7
year, week, dow = dt.isocalendar()
# Find the first day of the week.
if dow == week_start:
start_date = dt
elif dow >= week_start:
# subtract `dow` number days to get the first day
start_date = dt - datetime.timedelta(days=dow - week_start)
else:
# subtract the `dow` to `week_start` and the week size to get the first day
start_date = dt - datetime.timedelta(days=7 - (week_start - dow))
# Now, add 6 for the last day of the week
# (i.e., count up to Saturday if starts on Sunday)
end_date = start_date + datetime.timedelta(6)
return start_date, end_date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment