2017-03-16 205 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))