【问题标题】:Confusion surrounding datetime import (Strings & Dates)日期时间导入的混淆(字符串和日期)
【发布时间】:2022-01-03 08:20:36
【问题描述】:

我真的被我的这部分代码困住了,如果能从其他人那里得到一些输入,那就太棒了。这部分不是我写的,也无法联系到写的人(这是一个小组项目)。当您没有正确格式化输入时,它确实会出现错误(我们不需要对此项目进行验证,所以我不会担心),但我担心的是这些错误:

Traceback (most recent call last):
  File "/Users/mycomputer/PycharmProjects/project/main.py", line 46, in <module>
    stringsdates()
  File "/Users/mycomputer/PycharmProjects/project/main.py", line 29, in stringsdates
    birthmonth = birthday.month
AttributeError: 'str' object has no attribute 'month'

非常感谢任何帮助

import datetime

def yearadd(date):
    test = datetime.timedelta(days=365)
    return date + test

def stringsdates():
    # Inputs for first and last name, start date and birthday along with yearly salary.

    firstname = input("What is your first name? ")
    lastname = input("What is your last name? ")
    startdate = input("What is the date you started with the company? (YYYY MM DD) ")
    birthday = input("What is your birthday? (YYYY MM DD) ")
    yearlysal = input("What is your yearly salary? ")

    # ♡ Processing
    startdate = datetime.datetime.strptime(startdate, "%Y %m %d")
    birthdate = datetime.datetime.strptime(birthday, "%Y %m %d")
    yearhired = startdate.year
    birthmonth = birthday.month
    today = datetime.datetime.today()

    formatfullname = (firstname + lastname + ", " + firstname[0] + "." + lastname + ", " + lastname + ", " + firstname[
        0] + ".")
    employeenum = firstname.upper()[0] + lastname.upper()[0] + "-" + str(yearhired) + "-" + str(birthmonth)
    reviewdate = yearadd(yearhired)
    nextbday = today - birthdate

    # ♡ Output
    print(formatfullname)
    print(employeenum)
    print(reviewdate)
    print(nextbday)
    print(yearlysal)

【问题讨论】:

  • 您访问的是birthday.month,但也许您的意思是birthdate.monthbirthday 来自您的输入,因此它将是一个字符串

标签: python string datetime object attributeerror


【解决方案1】:

您正在尝试将birthmonth 读取为birthday.month,其中birthday 是您从用户那里读取的字符串,并且由于字符串类型没有与之关联的月份属性,因此您会收到错误消息。您可能打算使用的是转换后的日期时间对象birthdate

birthmonth = birthdate.month

【讨论】:

  • 成功了,非常感谢!现在有多个新错误,但生日更改是一个很好的错误:) 文件“/Users/user/PycharmProjects/project/main.py”,第 30 行,在 stringsdates reviewdate = yearadd(yearhired) 文件“/Users/user /PycharmProjects/project/main.py", line 8, in yearadd return date + test TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta' 我很抱歉我的经验不足 :( 我有一种感觉它在某个地方想要一个 int 但我不确定如果这是解决方案如何实现它?
  • 很高兴为您提供帮助。至于您的新错误,您似乎正在尝试添加 test 这是一个带有整数的 datetime.timedelta 对象。我想你可以通过使用test.days 来解决这个问题。所以只需将其更改为return date + test.days。如果您觉得有帮助,请务必接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多