Python Django-自日期起仅获取一年

Python Django-自日期起仅获取一年,python,django,python-3.x,Python,Django,Python 3.x,我正在使用的代码: #models.py class Profile(models.Model): date_of_birth = models.DateField(null=True, blank=True) #template.html <span>Age: <small>{{ object.date_of_birth|timesince }}</small></span> #models.py 类配置文件(models.Model

我正在使用的代码:

#models.py
class Profile(models.Model):
    date_of_birth = models.DateField(null=True, blank=True)

#template.html
<span>Age: <small>{{ object.date_of_birth|timesince }}</small></span>
#models.py
类配置文件(models.Model):
出生日期=models.DateField(null=True,blank=True)
#template.html
年龄:{{object.date}出生日期{timesince}

这个代码给了我一个例子:25年,3个月。我该怎么做才能让我在这片土地上呆上几年?(在本例中为25)有什么想法吗?谢谢。

在您的类中添加一个函数以仅返回以下出生年份我已添加了
get_birth\u year
函数以仅返回年份

from datetime import datetime

class Profile(models.Model):
    date_of_birth = models.DateField(null=True, blank=True)

    def get_birth_year(self):
        return datetime.now().year - self.date_of_birth.year 
现在,您可以访问get_出生年份以仅在模板中获取出生年份

#template.html
<span>Age: <small>{{ object.get_birth_year }}</small></span>
#template.html
年龄:{object.get_birth_year}

参考此内容,您可以编写一个自定义模板标记,以去除剩余部分
timesince(date\u time)。split(',')[0]
我不确定该函数是否在所有情况下都返回有效年份,但我认为现在是最好的解决方案。