Created
March 7, 2013 19:27
-
-
Save bradmontgomery/5110985 to your computer and use it in GitHub Desktop.
Given a Date, calculate the first/last dates for the week. This assumes weeks start on Sunday and end on Saturday (common in the US).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import timedelta | |
def week_range(date): | |
"""Find the first & last day of the week for the given day. | |
Assuming weeks start on Sunday and end on Saturday. | |
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 = date.isocalendar() | |
# Find the first day of the week. | |
if dow == 7: | |
# Since we want to start with Sunday, let's test for that condition. | |
start_date = date | |
else: | |
# Otherwise, subtract `dow` number days to get the first day | |
start_date = date - timedelta(dow) | |
# Now, add 6 for the last day of the week (i.e., count up to Saturday) | |
end_date = start_date + 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