IT이야기

python의 탄생일로부터 나이

cyworld 2022. 3. 21. 08:55
반응형

python의 탄생일로부터 나이

오늘 날짜와 사람의 생년월일을 어떻게 파이썬에서 찾을 수 있을까?생년월일은 Django 모델의 DateField에서 왔다.

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))
from datetime import date

def calculate_age(born):
    today = date.today()
    try: 
        birthday = born.replace(year=today.year)
    except ValueError: # raised when birth date is February 29 and the current year is not a leap year
        birthday = born.replace(year=today.year, month=born.month+1, day=1)
    if birthday > today:
        return today.year - born.year - 1
    else:
        return today.year - born.year

업데이트: 대니의 솔루션을 사용하십시오.

from datetime import date

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

할 수 datetime.timedelta:

from datetime import date, timedelta

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

@[Tomasz Zielinski]와 @Wiliams python-dateutil에서 제안한 대로 5줄만 하면 된다.

from dateutil.relativedelta import *
from datetime import date
today = date.today()
dob = date(1982, 7, 5)
age = relativedelta(today, dob)

>>relativedelta(years=+33, months=+11, days=+16)`

가장 간단한 방법은python-dateutil

import datetime

import dateutil

def birthday(date):
    # Get the current date
    now = datetime.datetime.utcnow()
    now = now.date()

    # Get the difference between the current date and the birthday
    age = dateutil.relativedelta.relativedelta(now, date)
    age = age.years

    return age
from datetime import date

def age(birth_date):
    today = date.today()
    y = today.year - birth_date.year
    if today.month < birth_date.month or today.month == birth_date.month and today.day < birth_date.day:
        y -= 1
    return y

불행히도, 당신은 타임라타를 그냥 사용할 수 없다. 타임라타는 그것이 사용하는 가장 큰 단위는 낮이고 윤년은 계산이 무효가 될 것이기 때문이다.그러므로 몇 년을 찾아보고 마지막 해가 꽉 차지 않으면 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

업데이트:

이 해결책은 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

업데이터2:

여러 통화를 호출하는 중now()공연히 히트한 것은 우스꽝스러운 일이다. 그것은 아주 특별한 경우를 제외하고는 전혀 문제가 되지 않는다.변수를 사용하는 진짜 이유는 데이터 부조화의 위험 때문이다.

django 템플릿을 사용하여 이 페이지를 인쇄하려는 경우 다음 항목으로 충분할 수 있다.

{{ birth_date|timesince }}

이 시나리오에서 고전적인 gotcha는 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

대니솔루션으로 확장하지만, 젊은 층의 나이를 보고하는 다양한 방법이 있다(참고, 오늘은datetime.date(2015,7,17)):

def calculate_age(born):
    '''
        Converts a date of birth (dob) datetime object to years, always rounding down.
        When the age is 80 years or more, just report that the age is 80 years or more.
        When the age is less than 12 years, rounds down to the nearest half year.
        When the age is less than 2 years, reports age in months, rounded down.
        When the age is less than 6 months, reports the age in weeks, rounded down.
        When the age is less than 2 weeks, reports the age in days.
    '''
    today = datetime.date.today()
    age_in_years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    months = (today.month - born.month - (today.day < born.day)) %12
    age = today - born
    age_in_days = age.days
    if age_in_years >= 80:
        return 80, 'years or older'
    if age_in_years >= 12:
        return age_in_years, 'years'
    elif age_in_years >= 2:
        half = 'and a half ' if months > 6 else ''
        return age_in_years, '%syears'%half
    elif months >= 6:
        return months, 'months'
    elif age_in_days >= 14:
        return age_in_days/7, 'weeks'
    else:
        return age_in_days, 'days'

샘플 코드:

print '%d %s' %calculate_age(datetime.date(1933,6,12)) # >=80 years
print '%d %s' %calculate_age(datetime.date(1963,6,12)) # >=12 years
print '%d %s' %calculate_age(datetime.date(2010,6,19)) # >=2 years
print '%d %s' %calculate_age(datetime.date(2010,11,19)) # >=2 years with half
print '%d %s' %calculate_age(datetime.date(2014,11,19)) # >=6 months
print '%d %s' %calculate_age(datetime.date(2015,6,4)) # >=2 weeks
print '%d %s' %calculate_age(datetime.date(2015,7,11)) # days old

80 years or older
52 years
5 years
4 and a half years
7 months
6 weeks
7 days
import datetime

오늘 날짜

td=datetime.datetime.now().date() 

너의 생년월일

bd=datetime.date(1989,3,15)

당신의 나이

age_years=int((td-bd).days /365.25)

사람의 나이를 나이, 월, 일 중 하나로 찾는 해결책이 여기에 있다.

사람의 생년월일은 2012-01-17이라고 하자.T00:00:00 따라서 2013-01-16T00:00:00의 그의 나이는 11개월이 될 것이다.

또는 그가 2012-12-17T00:00:00에 태어났다면 2013-01-12T00:00:00의 나이는 26일이 될 것이다.

또는 그가 2000-02-29년에 태어났다면T00:00:00, 2012-02-29세 나이T00:00:0012년이 될 것이다.

날짜/시간을 가져오십시오.

암호는 다음과 같다.

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()

그리고,

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")

이제 2000-02-29와 같은 문자열로 get_date_format()을 공급해야 한다.T00:00:00

이를 get_person_age(date_birth, date_today)를 얻기 위해 공급할 날짜 유형 개체로 변환한다.

함수 get_person_age(date_birth, date_today)는 문자열 형식으로 나이를 반환한다.

나는 정확한 구현을 보지 못했기 때문에 내 것을 이렇게 되뇌었다...

    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)

29일에 태어난 2월 28일에 "18"이라고 가정하는 것은 잘못된 것이다.한계 교환은 제외될 수 있다...그것은 단지 내 코드에 대한 개인적인 편의일 뿐이다 :)

Danny W. Adair Answer까지 연장하여 월을 얻으십시오.

def calculate_age(b):
    t = date.today()
    c = ((t.month, t.day) < (b.month, b.day))
    c2 = (t.day< b.day)
    return t.year - b.year - c,c*12+t.month-b.month-c2

날짜/시간 가져오기

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

읽기 쉽고 이해하기 쉬운 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

serializers.py

age = serializers.SerializerMethodField('get_age')

class Meta:
    model = YourModel
    fields = [..,'','birthdate','age',..]


import datetime

def get_age(self, instance):
    return datetime.datetime.now().year - instance.birthdate.year

이 모든 것을 하기 위해 파이선 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}')

참조URL: https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python

반응형