Calculate "age" MongoDB document DateTimeField Flask
Question: I'm using python 3.4 and flask 0.10 with MongoDB 2.6 standard for my
application. With mongo Document. I want to calculate the "age" or "years"
from Persons just with its Birthday. I have this code:

    
    
    import datetime
    from Personal import db
    
    class Person(db.Document):
        ID = db.StringField(required=True, primary_key=True, unique=True, max_length=6)
        name = db.StringField(required=True)
        birthday = db.DateTimeField(required=True)
        age = ########
    

I tried with

    
    
    age = int(datetime.datetime.now.year) - int(birthday).year
    

And I know it's wrong. I already read the Mongo Documents guide, didn't help:

<http://docs.mongoengine.org/guide/defining-documents.html>

Please, Indeed help with DateTime operations

Thanks


Answer: The feature you're looking for could be in python instead of mongodb, using a
`property` you can achieve that quite easily:

    
    
    class Person(db.Document):
        ID = db.StringField(required=True, primary_key=True, unique=True, max_length=6)
        name = db.StringField(required=True)
        birthday = db.DateTimeField(required=True)
    
        @property
        def age(self):
            return ((datetime.datetime.now() - self.birthday).days) / 365
    

with that class, you're allowed to do this:

    
    
    >>> p = Person(name='rafael', birthday=datetime.datetime(year=1990, day=1, month=1))
    >>> p.age
    24
    

But you won't be able to query by age, since it's not kept on your database.

