在python中计算年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42843399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:11:55  来源:igfitidea点击:

Calculating age in python

pythoncalculator

提问by A. Gunter

I am attempting to create a code where the user is asked for their date of birth and today's date in order to determine their age. What I have written so far is:

我正在尝试创建一个代码,要求用户提供他们的出生日期和今天的日期以确定他们的年龄。到目前为止我写的是:

print("Your date of birth (mm dd yyyy)")
Date_of_birth = input("--->")

print("Today's date: (mm dd yyyy)")
Todays_date = input("--->")


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

age = calculate_age(Date_of_birth)

However it is not running like I would hope. Could someone explain to me what I am doing wrong?

然而,它并没有像我希望的那样运行。有人可以向我解释我做错了什么吗?

回答by Attie

So close!

很近!

You need to convert the string into a datetime object before you can do calculations on it - see datetime.datetime.strptime().

您需要先将字符串转换为日期时间对象,然后才能对其进行计算 - 请参阅datetime.datetime.strptime()

For your date input, you need to do:

对于您的日期输入,您需要执行以下操作:

datetime.strptime(input_text, "%d %m %Y")
#!/usr/bin/env python3

from datetime import datetime, date

print("Your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")

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

age = calculate_age(date_of_birth)

print(age)


PS: I urge you to use a sensible order of input - dd mm yyyyor the ISO standard yyyy mm dd

PS:我敦促您使用合理的输入顺序 -dd mm yyyy或 ISO 标准yyyy mm dd

回答by Dani Medina

This should work :)

这应该有效:)

from datetime import date

def ask_for_date(name):
    data = raw_input('Enter ' + name + ' (yyyy mm dd): ').split(' ')
    try:
        return date(int(data[0]), int(data[1]), int(data[2]))
    except Exception as e:
        print(e)
        print('Invalid input. Follow the given format')
        ask_for_date(name)


def calculate_age():
    born = ask_for_date('your date of birth')
    today = date.today()
    extra_year = 1 if ((today.month, today.day) < (born.month, born.day)) else 0
    return today.year - born.year - extra_year

print(calculate_age())

回答by Yogesh Manghnani

You can also use date time library in this manner. This calculates the age in years and removes the logical error that returns wrong age due to the month and day properties

您也可以以这种方式使用日期时间库。这将计算以年为单位的年龄并消除由于月和日属性而返回错误年龄的逻辑错误

Like a person born on 31 July 1999 is a 17 year old till 30 July 2017

就像 1999 年 7 月 31 日出生的人在 2017 年 7 月 30 日之前是 17 岁

So here's the code :

所以这是代码:

import datetime

#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))

currentDate = datetime.datetime.today().date()

#some calculations here 
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day

#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)

# some decisions
if monthVeri < 0 :
    age = age-1
elif dateVeri < 0 and monthVeri == 0:
    age = age-1


#lets print the age now
print("Your age is {0:d}".format(age))

回答by saeede

 from datetime import datetime, date
def calculateAge(birthDate): 
    today = date.today() 
    age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day)) 
    return age 
d=input()
year=d[0:4]
month=d[5:7]
day=d[8:]
if int(month)<=0 or int(month)>12:
    print("WRONG")
elif int(day)<=0 or int(day)>31:
    print("WRONG")
elif int(month)==2 and int(day)>29:
    print("WRONG")
elif int(month) == 4 or int(month) == 6 or int(month) == 9 or int(month) ==11 and int(day) > 30:
    print("WRONG")
else:       
    print(calculateAge(date(int(year),int(month),int(day))))

This code will work correctly for every date.

此代码将适用于每个日期。