Python datetime日期处理报错:'str'对象无'month'属性问题求助
错误根因
本次报错的核心是变量名误用:
- 通过
input()获取的birthday为字符串类型,后续代码已经通过datetime.datetime.strptime()方法将其转换为datetime类型的birthdate变量,但第29行调用.month属性时依然使用了原始的字符串变量birthday,字符串不存在month属性,因此触发报错。
额外潜在问题
除上述直接报错外,代码还存在2处逻辑错误会导致后续运行失败:
yearadd()函数要求传入datetime类型参数才能执行时间加法,但reviewdate = yearadd(yearhired)中传入的yearhired是int类型的年份数值,会触发类型错误nextbday = today - birthdate计算得到的是出生日期到当前时间的总天数,并非下一个生日的日期,不符合业务逻辑预期
修复后的完整代码
import datetime def yearadd(date): test = datetime.timedelta(days=365) return date + test def stringsdates(): # 输入姓名、入职日期、生日、年薪 firstname = input("请输入你的名:") lastname = input("请输入你的姓:") startdate = input("请输入你的入职日期(格式 年 月 日,示例:2020 05 10):") birthday = input("请输入你的出生日期(格式 年 月 日,示例:1995 11 25):") yearlysal = input("请输入你的年薪:") # ♡ 数据处理 startdate = datetime.datetime.strptime(startdate, "%Y %m %d") birthdate = datetime.datetime.strptime(birthday, "%Y %m %d") yearhired = startdate.year # 修复1:使用转换后的datetime类型变量birthdate获取月份 birthmonth = birthdate.month today = datetime.datetime.today() formatfullname = (lastname + firstname + ", " + firstname[0] + "." + lastname + ", " + lastname + ", " + firstname[ 0] + ".") employeenum = firstname.upper()[0] + lastname.upper()[0] + "-" + str(yearhired) + "-" + str(birthmonth) # 修复2:给yearadd传入datetime类型的入职日期,而非整数类型的入职年份 reviewdate = yearadd(startdate) # 修复3:调整下一个生日的计算逻辑 this_year_bday = birthdate.replace(year=today.year) if this_year_bday < today: nextbday = this_year_bday.replace(year=today.year + 1) else: nextbday = this_year_bday # ♡ 结果输出 print(formatfullname) print(employeenum) print(reviewdate.strftime("%Y-%m-%d")) print(nextbday.strftime("%Y-%m-%d")) print(yearlysal)
内容的提问来源于stack exchange,提问作者snowbuns
相关产品推荐
相关产品推荐

