我怎么能从今天的日期和一个人的出生日期找到一个python年龄?出生日期来自Django模型中的DateField。


当前回答

进口日期时间

def age(date_of_birth):
    if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
        return datetime.date.today().year - date_of_birth.year - 1
    else:
        return datetime.date.today().year - date_of_birth.year

在你的情况下:

import datetime

# your model
def age(self):
    if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
        return datetime.date.today().year - self.birthdate.year - 1
    else:
        return datetime.date.today().year - self.birthdate.year

其他回答

from datetime import date

days_in_year = 365.2425    
age = int((date.today() - birth_date).days / days_in_year)

在Python 3中,你可以对datetime.timedelta执行除法:

from datetime import date, timedelta

age = (date.today() - birth_date) // timedelta(days=365.2425)

由于我没有看到正确的实现,我以这种方式重新编码了我的…

    def age_in_years(from_date, to_date=datetime.date.today()):
  if (DEBUG):
    logger.debug("def age_in_years(from_date='%s', to_date='%s')" % (from_date, to_date))

  if (from_date>to_date): # swap when the lower bound is not the lower bound
    logger.debug('Swapping dates ...')
    tmp = from_date
    from_date = to_date
    to_date = tmp

  age_delta = to_date.year - from_date.year
  month_delta = to_date.month - from_date.month
  day_delta = to_date.day - from_date.day

  if (DEBUG):
    logger.debug("Delta's are : %i  / %i / %i " % (age_delta, month_delta, day_delta))

  if (month_delta>0  or (month_delta==0 and day_delta>=0)): 
    return age_delta 

  return (age_delta-1)

如果你出生在2月29日,你就认为自己在2月28日是“18岁”,这是错误的。 交换边界可以省略…这只是我的代码的个人方便:)

一个比@DannyWAdairs稍微优雅一点的解决方案可能是使用.timetuple()方法[Python-doc]:

from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - (today.timetuple()[1:3] < born.timetuple()[1:3])

你可以很容易地使用这个来进一步推广它,将其粒度增加到秒,这样,如果它大于或等于当天的秒数,年龄就会增加,例如born是一个datetime对象:

from datetime import datetime

def calculate_age_with_seconds(born):
    today = datetime.now()
    return today.year - born.year - (today.timetuple()[1:6] < born.timetuple()[1:6])

这对于date或datetime对象都适用。

考虑到int(True)是1,int(False)是0,元组比较从左到右,这可以做得更简单:

from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

下面是一个用年、月或日来计算一个人年龄的方法。

假设一个人的出生日期是2012-01-17T00:00:00 因此,他的年龄在2013-01-16T00:00:00将是11个月

或者他出生在2012-12-17T00:00:00, 他的年龄在2013-01-12T00:00:00将是26天

或者他出生在2000-02-29T00:00:00, 他的年龄在2012-02-29T00:00:00将是12岁

您将需要导入datetime。

代码如下:

def get_person_age(date_birth, date_today):

"""
At top level there are three possibilities : Age can be in days or months or years.
For age to be in years there are two cases: Year difference is one or Year difference is more than 1
For age to be in months there are two cases: Year difference is 0 or 1
For age to be in days there are 4 possibilities: Year difference is 1(20-dec-2012 - 2-jan-2013),
                                                 Year difference is 0, Months difference is 0 or 1
"""
years_diff = date_today.year - date_birth.year
months_diff = date_today.month - date_birth.month
days_diff = date_today.day - date_birth.day
age_in_days = (date_today - date_birth).days

age = years_diff
age_string = str(age) + " years"

# age can be in months or days.
if years_diff == 0:
    if months_diff == 0:
        age = age_in_days
        age_string = str(age) + " days"
    elif months_diff == 1:
        if days_diff < 0:
            age = age_in_days
            age_string = str(age) + " days"
        else:
            age = months_diff
            age_string = str(age) + " months"
    else:
        if days_diff < 0:
            age = months_diff - 1
        else:
            age = months_diff
        age_string = str(age) + " months"
# age can be in years, months or days.
elif years_diff == 1:
    if months_diff < 0:
        age = months_diff + 12
        age_string = str(age) + " months" 
        if age == 1:
            if days_diff < 0:
                age = age_in_days
                age_string = str(age) + " days" 
        elif days_diff < 0:
            age = age-1
            age_string = str(age) + " months"
    elif months_diff == 0:
        if days_diff < 0:
            age = 11
            age_string = str(age) + " months"
        else:
            age = 1
            age_string = str(age) + " years"
    else:
        age = 1
        age_string = str(age) + " years"
# The age is guaranteed to be in years.
else:
    if months_diff < 0:
        age = years_diff - 1
    elif months_diff == 0:
        if days_diff < 0:
            age = years_diff - 1
        else:
            age = years_diff
    else:
        age = years_diff
    age_string = str(age) + " years"

if age == 1:
    age_string = age_string.replace("years", "year").replace("months", "month").replace("days", "day")

return age_string

以上代码中使用的一些额外函数是:

def get_todays_date():
    """
    This function returns todays date in proper date object format
    """
    return datetime.now()

And

def get_date_format(str_date):
"""
This function converts string into date type object
"""
str_date = str_date.split("T")[0]
return datetime.strptime(str_date, "%Y-%m-%d")

现在,我们必须为get_date_format()提供像2000-02-29T00:00:00这样的字符串

它将把它转换为日期类型对象,该对象将被提供给get_person_age(date_birth, date_today)。

函数get_person_age(date_birth, date_today)将返回字符串格式的年龄。