Since you know roughly when it will fall, the easiest way to find the first week might be to do a linear search for it. By the rules you give, the end of the week will fall on the first Saturday on or after the 4th of January. You can find this by:
def first_saturday(year):
candidate = dt.datetime(year, 1, 4)
day = dt.timedelta(days=1)
while candidate.weekday() != 6:
candidate += day
return candidate
If you wanted, you could make this read a bit nicer by implementing a datecount
function analgous to itertools.count
, so that you have:
first_saturday = next(day for day in
datecount(datetime(year, 1, 4), timedelta(days=1))
if day.weekday() == 6)
From there, find the starting Sunday by subtracting 6 days from the starting Saturday. Then the number of weeks should be:
(arbitrary_day - first_sunday) // timedelta(days=7)
This will count from zero.
To find out which year a particular day belongs in, there are only three possibilities: its gregorian calendar year, the year after, or the year before. The one you're interested in is the lowest of those three where first_sunday(year) <= arbitrary_date
.