【问题标题】:I want to get the user date of birth in python我想在 python 中获取用户的出生日期
【发布时间】:2020-07-17 14:16:34
【问题描述】:
bdate = input("Type your Date of birth (ie.10/11/2011) : ")
print(bdate)
day, month, year = map(int, bdate.split('/'))
birth_date = datetime.date(day, month, year)
print(birth_date)
today = datetime.datetime.now().strftime("%Y")
print(today)
age = today - birth_date.year ```

错误:day is out of range for month如何解决此错误

【问题讨论】:

  • birth_date = datetime.date(year,month,day) 不是(day,month,year)

标签: python python-3.x date python-datetime


【解决方案1】:

就像@sushanth 说你可以使用 relativedelta。

但为了了解您的代码有什么问题,我已经更正了它:

import datetime

bdate = input("Type your Date of birth (ie.10/11/2011) : ")

day, month, year = map(int, bdate.split('/'))
birth_date = datetime.date(year, month, day)

current_year = datetime.datetime.now().year

age = current_year - birth_date.year

print(age)

第一个问题是,datetime.date 具有以下属性: 年、月、日而不是日、月、年。

第二个问题是你不能从一个整数中减去一个字符串。相反,您可以使用 datetime.datetime.now().year 来获取当前年份 (int)。

【讨论】:

    【解决方案2】:

    试试这个,使用relativedelta

    from dateutil.relativedelta import relativedelta
    from datetime import datetime
    
    bdate = input("Type your Date of birth (ie.10/11/2011) : ")
    
    # convert the input string to datetime-object.
    birth_date = datetime.strptime(bdate, "%d/%m/%Y")
    
    print(f"{relativedelta(datetime.now(), birth_date).years} yrs")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      相关资源
      最近更新 更多