Author Topic: [Python] calculate age and days until next birthday  (Read 3007 times)

0 Members and 1 Guest are viewing this topic.

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
[Python] calculate age and days until next birthday
« on: August 13, 2012, 06:40:50 pm »
Can't remember if this was posted or not... I can't seem to find it...

Code: (python) [Select]
def calculateAge(self, date):
    '''Calculates the age and days until next birthday
       from the given birth date to display in the results'''
    returnStr = ''
    try:
        for i in './- ':
            if (date.find(i) != -1):
                date = date.split(i)
                break;
        birthdate = datetime.date(int(date[0]), int(date[1]), int(date[2]))
        today = datetime.date.today()

        if (today.month > birthdate.month):
            nextYear = datetime.date(today.year + 1, birthdate.month, birthdate.day)
        elif (today.month < birthdate.month):
            nextYear = datetime.date(today.year, today.month + (birthdate.month - today.month), birthdate.day)
        elif (today.month == birthdate.month):
            if (today.day > birthdate.day):
                nextYear = datetime.date(today.year + 1, birthdate.month, birthdate.day)
            elif (today.day < birthdate.day):
                nextYear = datetime.date(today.year, birthdate.month, today.day + (birthdate.day - today.day))
            elif (today.day == birthdate.day):
                nextYear = 0

        age = today.year - birthdate.year

        if nextYear == 0: #if today is the birthday
            returnStr = '%d, days until %d: %d' % (age, age+1, 0)
        else:
            daysLeft = nextYear - today
            returnStr = '%d, days until %d: %d' % (age, age+1, daysLeft.days)
    except:
        returnStr = 'date not entered or format incorrect'
    return returnStr