It’s simple mathematics. There are fifty-two weeks in a year, and I am a little over thirty-six and a half years old, which means I have lived through about nineteen hundred weekends.
When you talk about life in terms of weeks or months or years, it sounds long. When you think about it in weekends, it seems very short, and the concept of a weekend seems so much more precious. I probably didn’t appreciate my first 260 or so weekends very much, from ages zero to five. And now, I have less than two hundred weekends until my fortieth birthday, and another 520 after that until my fiftieth. If there’s anything I want to accomplish before then, I’d better get started soon!
But, before that, why not write a short Python routine to compute the number of weekends between two dates? For simplicity’s sake, we’ll treat the second date as a Pythonic fencepost: we’ll count the number of weekends that occur beginning at the start of the first date, and ending at the end of the day just before the second date.
The simple approach is just to take the difference in days between the two dates, and divide by 7. That will work most of the time, but on occasion there’s an extra Saturday or Sunday (or two) between the two dates. So, we’ll add half a weekend for each of the leftover days that’s a Saturday or Sunday (i.e. the date’s isoweekday()
is 6 or 7). To determine that, we’ll back up from the end date, by a number of days equal to the leftover days, and then figure out whether the span of days encompasses days 6 and 7. (Guess what mathematical problem I was mulling over in bed this morning when I couldn’t sleep?)
def weekends_between(d1,d2): days_between = (d2-d1).days weekends, leftover = divmod(days_between,7) if leftover: start_day = (d2-timedelta(leftover)).isoweekday() end_day = start_day+leftover if start_day<=6 and end_day>6: weekends +=.5 if start_day<=7 and end_day>7: weekends +=.5 return weekends
Let’s test it out to see how it works:
>>> from datetime import date, timedelta >>> weekends_between(date(2004,10,2),date(2004,10,5)) 1.0 >>> weekends_between(date(2004,10,3),date(2004,10,5)) 0.5 >>> weekends_between(date(2004,10,1),date(2004,10,10)) 1.5 >>> weekends_between(date(2004,10,1),date(2004,10,11)) 2.0
Woohoo. So, I’ve lived through 1914 weekends, counting this one. And apparently, I was born on a Saturday. Obviously I had the right idea, starting off life on a weekend. 🙂
So how many weekends do you have left in your life, based on your projected life expectancy? Give it some thought, and enjoy your weekend.
How about how many full moons (using mx.DateTime):
from mx.DateTime import today, DateTime
def howmanymoons(d1, d2):
mooncycle = (29*24*60)+(17*60)+7 # in minutes
return int((d2-d1).minutes/mooncycle)
print howmanymoons(DateTime(1969,4,30), today())