Jon Loyens RSS

Technologist, Tennis Fan, Musician

Archive

Jan
2nd
Fri
permalink

Date Checking Python

So Python’s datetime library makes it pretty easy to check dates and it’s got an awesome timedelta class to make date math super simple.  We’ve got a client that we’re building out a social networking site for (in Django of course) and today I was working on a requirement for them that certain parts of the profile could only be publicly displayed if the user was over 18.

I thought this would be a perfect use of the timedelta class but alas, the you can only give create timedeltas in increments less than months (ie. weeks, days, minutes, seconds, milliseconds only).  First I thought that I could just multiply weeks but then you run into leap year issues etc.  Instead here’s a handy little function I added to our user profile model that’s still a pretty nice example of Python datetime code (note: we allow our users not to disclose their age but assume they’re underage if they haven’t):

def is_of_age(self):
  if self.dob:
    min_dob = datetime.date.today()
    min_dob = datetime.date(year=min_dob.year-18,
       month=min_dob.month, day=min_dob.day)
    return min_dob >= self.dob
return False