Opened 14 years ago

Closed 14 years ago

#14157 closed (invalid)

Birthday calculation failing silently

Reported by: nil_von_9wo Owned by: nobody
Component: Uncategorized Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a model:

class Fighter (models.Model):
    name = models.CharField(max_length=100)
    birth_date = models.DateField(blank=True, null=True)

    def age(self):
        return calculate_age(self.birth_date)

calculate_age is as follow:

def calculate_age(born):
    today = datetime.datetime.today()
    try: # raised when birth day is February 29 and the current year is not a leap year
        birthday = born.replace(year=today.year)
    except ValueError:
        birthday = born.replace(year=today.year, day=born.day-1)

    import pdb; pdb.set_trace();
    
    if birthday > today:
        return today.year - born.year -1 
    else:
        return today.year - born.year

This function works perfectly from the command line.

However, as it is, from within a running django server, Fighter.age() returns no results.

By experimenting, I learned Fighter.age() will return a result if I return something (anything) in calculate_age() before it hits

if birthday > today:

By returning both values before that point, I verified that neither was "None", however they may not be the same data type.

I'm going to try casting them to match the type, but I was advised I should report this incident.

Change History (2)

comment:1 by nil_von_9wo, 14 years ago

For whatever its worth, I've verified that the problem is in fact a type problem which could be solved by including the line:

birthday_datetime = datetime.datetime.combine(birthday,datetime.time())

but even so, the silent failure made it very difficult to figure this out.

comment:2 by Ramiro Morales, 14 years ago

Resolution: invalid
Status: newclosed

You are declaring the today var as a datetime and are trying to compare it with a date value (born, obtained from the Django DateField).

>>> import datetime
>>> born =  datetime.date(1971, 11, 26)
>>> today = datetime.date.today()
>>> try:
...     bday = born.replace(year=today.year)
... except ValueError:
...     bday = born.replace(year=today.year, day=born.day-1)
...
>>> bday
datetime.date(2010, 11, 26)
>>> bday > today
True
>>> wrong_today = datetime.datetime.today()
>>> bday > wrong_today
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.date

Please review your code because I doubt it is working on the command line in its current form.

Closing ticket as invalid because it's a basic Python problem.

Note: See TracTickets for help on using tickets.
Back to Top