2017-03-16 169 views
2

我试图创造一个用户被询问他们的出生和今天的日期的日期,以确定他们的年龄代码。我到目前为止写的是:计算年龄在python

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) 

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

+0

offtopic:永远不要用caps启动变量的名称,而应使用'date_of_birth'和'todays_date'。 – dabadaba

+1

*它如何不按照你的希望运行?请解释。 –

+0

它根本没有运行,它爆炸并说'str'对年份没有任何属性 –

回答

7

太近了!

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

为了您的数据输入,你需要做的:

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:我强烈建议你使用输入的一个明智的秩序 - dd mm yyyy或ISO标准yyyy mm dd

+2

'毫米DD yyyy'在美国非常明智和普遍 – Simon

+4

不幸的是,是的... – Attie

+0

非常感谢你的帮助!这为我解决了它! –

1

这应该工作:)

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

您也可以以这种方式使用日期时间库。这种计算岁,并删除返回错误岁时因的月份和日期的属性

一样出生于1999年7月31日一个人是7月17岁至30 2017年

因此,这里的逻辑错误代码:

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