计算年龄 python
Calculating age in 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)
然而,它并不像我希望的那样 运行。有人可以向我解释我做错了什么吗?
太近了!
您需要先将字符串转换为日期时间对象,然后才能对其进行计算 - 请参阅 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
这应该有效:)
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())
您也可以通过这种方式使用日期时间库。这将计算年龄,并消除 returns 由于月份和日期属性
导致年龄错误的逻辑错误
比如 1999 年 7 月 31 日出生的人在 2017 年 7 月 30 日之前是 17 岁
代码如下:
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))
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))))
此代码适用于每个日期。
我正在尝试创建一个代码,要求用户提供他们的出生日期和今天的日期以确定他们的年龄。目前我写的是:
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)
然而,它并不像我希望的那样 运行。有人可以向我解释我做错了什么吗?
太近了!
您需要先将字符串转换为日期时间对象,然后才能对其进行计算 - 请参阅 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
这应该有效:)
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())
您也可以通过这种方式使用日期时间库。这将计算年龄,并消除 returns 由于月份和日期属性
导致年龄错误的逻辑错误比如 1999 年 7 月 31 日出生的人在 2017 年 7 月 30 日之前是 17 岁
代码如下:
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))
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))))
此代码适用于每个日期。