python - Python:如何从输入的出生日期和当前日期中找到年龄?
问题描述
我制作了一个程序,它要求用户将他们的出生日期输入为整数,然后我尝试将出生日期转换为一种格式,然后与导入的当前日期进行比较。但是,我正在努力确定可在 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)
解决方案
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))
推荐阅读
- flutter - Flutter with tflite 和可教机器查询
- spring-boot - Spring Boot Dashboard 未在 VSCode 中自动激活
- javascript - 确认支付 API 和 JavaScript
- c# - 解决 OAuth 令牌刷新中的竞争条件
- python - 如何网格扩展动态调整窗口大小?
- php - Redux 框架字段类型编辑器未显示在自定义选项上
- unity3d - WebGL Unity 外部 StreamingAssets
- reactjs - AWS S3 生成大量请求
- python - 将 MySQL 作为后端数据库连接到 Django 时出错
- python - 如何通过torch.max返回的索引获取最大值?