Skip to content

Instantly share code, notes, and snippets.

@idan
Created March 17, 2014 10:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idan/9596928 to your computer and use it in GitHub Desktop.
Save idan/9596928 to your computer and use it in GitHub Desktop.
Python ISO week for date
import datetime
def week_for_date(target):
"""Given a target date, return a start and end for that date's ISO week.
The returned tuple includes two datetime.date's, (start, end):
start: midnight on the first day of the ISO week containing the target
end: midnight on the first day following the ISO week containing the target
Note that the end date represents the first date _not_ in the target week,
but rather an upper bound, so the following must always be true:
start <= any date/time in the target's ISO week < end
"""
year, week, dow = target.isocalendar()
start = target.date() - datetime.timedelta(dow - 1) # ISO days of week are 1-based
end = start + datetime.timedelta(7)
return (start, end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment