在网上搜索后得到了以下两种方法来确定一个人的年龄。
只是想知道是否有更好的综合方法来计算和编写3.x版本的python。
第一个办法。。。
$ cat birth1.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
import datetime
year = datetime.datetime.now().year # getting current year from the system
year_of_birth = int(input("Enter Your Birth Year: "))
print("You are %i Year Old" % (year - year_of_birth))
结果。。
$ ./birth1.py
Enter Your Birth Year: 1981
You are 37 Year Old
第二条路。。。。
$ cat birth2.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
from datetime import datetime, date
print("Your date of birth (dd/mm/yyyy)")
date_of_birth = datetime.strptime(input("Please Put your age here: "), "%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("You are %i Year Old." % (age))
结果会产生。。
$ ./birth2.py
Your date of birth (dd/mm/yyyy)
Please Put your age here: 22/09/2015
You are 2 Year Old.