如何从django的datefield获取年份?

时间:2018-08-07 11:21:25

标签: python django

我想过生日。 所以我用self.birthday.year 但是会出错。 我该如何解决?

最诚挚的问候。

class User(AbstractUser):

# First Name and Last Name do not cover name patterns
# around the globe.

name = models.CharField(_("Name of User"), blank=True, max_length=255) #이름
gender = models.CharField(max_length=1, choices=CHOICES_GENDER) # 성
birthday = models.DateField(null=True) #생일

def calculate_age(self):
    import datetime
    return int((datetime.date.year - self.birthday.year) +1)

 age = property(calculate_age) #나이

2 个答案:

答案 0 :(得分:0)

问题是datetime.date.year不存在。您可以使用year获取date(或datetime)对象的.year,例如,可以使用today()now()

从功能上讲,该功能也不正确。如果我出生于1984年,那么我本身还不到35岁:这取决于当年是出生日期之前还是之后(例如2月9日)。

最后,如果self.birthday的值为None,可能会出错。在这种情况下,您可能还想返回None

因此,可能的解决方案是:

from datetime import date

class User(AbstractUser):

    # ...

    def calculate_age(self):
        bd = self.birthday
        if bd:
            td = date.today()
            return td.year - bd.year - ((td.month, td.day) < (bd.month, bd.day))

因此,我们首先计算today(),然后返回当前年份减去生日年份,如果今天仍在今年生日之前,则减去1。

如果用户未指定 生日,那么calculate_age(..)将返回None(一个可以解释为“未知”的值)。 / p>

时区仍然存在(且更难解决),因为时区:today在澳大利亚比在美国today还要远,因此可能取决于服务器和服务器的位置用户所在的位置-用户的年龄在他/她生日前一天过高,或在他/她生日前一天过低。这是一个很难解决的问题,因为我们在这里没有用户所在的位置的信息。

答案 1 :(得分:0)

尝试此解决方案,

from datetime import date


class User(AbstractUser):
    name = models.CharField(_("Name of User"), blank=True, max_length=255)
    gender = models.CharField(max_length=1, choices=CHOICES_GENDER)
    birthday = models.DateField(null=True)

    @property
    def calculate_age(self):
        if self.birthday:
            today = date.today()
            return today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day))
        return 0  # when "self.birthday" is "NULL"
相关问题