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


当前回答

在这种情况下,最经典的问题是如何对待2月29日出生的人。例如:你必须年满18岁才能投票、开车、买酒等等。如果你出生在2004-02-29,你被允许做这些事情的第一天是哪一天:2022-02-28,或2022-03-01?AFAICT,大多数是前者,但一些扫兴的人可能会说是后者。

下面的代码迎合了那一天出生的0.068%(大约)人口:

def age_in_years(from_date, to_date, leap_day_anniversary_Feb28=True):
    age = to_date.year - from_date.year
    try:
        anniversary = from_date.replace(year=to_date.year)
    except ValueError:
        assert from_date.day == 29 and from_date.month == 2
        if leap_day_anniversary_Feb28:
            anniversary = datetime.date(to_date.year, 2, 28)
        else:
            anniversary = datetime.date(to_date.year, 3, 1)
    if to_date < anniversary:
        age -= 1
    return age

if __name__ == "__main__":
    import datetime

    tests = """

    2004  2 28 2010  2 27  5 1
    2004  2 28 2010  2 28  6 1
    2004  2 28 2010  3  1  6 1

    2004  2 29 2010  2 27  5 1
    2004  2 29 2010  2 28  6 1
    2004  2 29 2010  3  1  6 1

    2004  2 29 2012  2 27  7 1
    2004  2 29 2012  2 28  7 1
    2004  2 29 2012  2 29  8 1
    2004  2 29 2012  3  1  8 1

    2004  2 28 2010  2 27  5 0
    2004  2 28 2010  2 28  6 0
    2004  2 28 2010  3  1  6 0

    2004  2 29 2010  2 27  5 0
    2004  2 29 2010  2 28  5 0
    2004  2 29 2010  3  1  6 0

    2004  2 29 2012  2 27  7 0
    2004  2 29 2012  2 28  7 0
    2004  2 29 2012  2 29  8 0
    2004  2 29 2012  3  1  8 0

    """

    for line in tests.splitlines():
        nums = [int(x) for x in line.split()]
        if not nums:
            print
            continue
        datea = datetime.date(*nums[0:3])
        dateb = datetime.date(*nums[3:6])
        expected, anniv = nums[6:8]
        age = age_in_years(datea, dateb, anniv)
        print datea, dateb, anniv, age, expected, age == expected

输出如下:

2004-02-28 2010-02-27 1 5 5 True
2004-02-28 2010-02-28 1 6 6 True
2004-02-28 2010-03-01 1 6 6 True

2004-02-29 2010-02-27 1 5 5 True
2004-02-29 2010-02-28 1 6 6 True
2004-02-29 2010-03-01 1 6 6 True

2004-02-29 2012-02-27 1 7 7 True
2004-02-29 2012-02-28 1 7 7 True
2004-02-29 2012-02-29 1 8 8 True
2004-02-29 2012-03-01 1 8 8 True

2004-02-28 2010-02-27 0 5 5 True
2004-02-28 2010-02-28 0 6 6 True
2004-02-28 2010-03-01 0 6 6 True

2004-02-29 2010-02-27 0 5 5 True
2004-02-29 2010-02-28 0 5 5 True
2004-02-29 2010-03-01 0 6 6 True

2004-02-29 2012-02-27 0 7 7 True
2004-02-29 2012-02-28 0 7 7 True
2004-02-29 2012-02-29 0 8 8 True
2004-02-29 2012-03-01 0 8 8 True

其他回答

为了便于阅读和理解,稍微修改了Danny的解决方案

    from datetime import date

    def calculate_age(birth_date):
        today = date.today()
        age = today.year - birth_date.year
        full_year_passed = (today.month, today.day) < (birth_date.month, birth_date.day)
        if not full_year_passed:
            age -= 1
        return age

一个比@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对象都适用。

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

    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岁”,这是错误的。 交换边界可以省略…这只是我的代码的个人方便:)

你可以使用Python 3来完成这一切。只需运行下面的代码就可以了。

# Creating a variables:

greeting = "Hello, "
name = input("what is your name?")
birth_year = input("Which year you were born?")
response = "Your age is "

# Converting string variable to int:

calculation = 2020 - int(birth_year) 


# Printing:

print(f'{greeting}{name}. {response}{calculation}')

不幸的是,您不能只使用时间数据,因为它使用的最大单位是日,闰年将使您的计算无效。因此,让我们找到年数,然后如果最后一年没有满,就按1调整:

from datetime import date
birth_date = date(1980, 5, 26)
years = date.today().year - birth_date.year
if (datetime.now() - birth_date.replace(year=datetime.now().year)).days >= 0:
    age = years
else:
    age = years - 1

Upd:

这个解决方案在2月29日开始时确实会导致一个异常。以下是正确的检查:

from datetime import date
birth_date = date(1980, 5, 26)
today = date.today()
years = today.year - birth_date.year
if all((x >= y) for x,y in zip(today.timetuple(), birth_date.timetuple()):
   age = years
else:
   age = years - 1

Upd2:

将多次调用now()称为性能损失是荒谬的,除非在极端特殊的情况下,否则这无关紧要。使用变量的真正原因是数据不一致的风险。