我制作了一个程序,它要求用户将他们的出生日期输入为整数,然后我尝试将出生日期转换为一种格式,然后与导入的当前日期进行比较。但是,我正在努力确定可以在 python 中使用的不同日期格式。
这是我的代码:
from datetime import datetime
print("This programme calculates your age from your date of birth")
dd=int(input("What day were you born? "))
mm=int(input("What month were you born, enter the month number:" ))
yyyy=int(input("What year were you born? Enter the full year: "))
today = datetime.today()
b1 = dd,mm,yyyy
newdate1 = datetime.strptime(b1, "%d/%m/%Y")
age = today.year - b1.year - ((today.month, today.day) < (b1.month, b1.day))
print(age)
答案 0 :(得分:1)
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))