【问题标题】:datetime.date: TypeError: an integer is required. Why?datetime.date:TypeError:需要一个整数。为什么?
【发布时间】:2013-11-26 05:05:27
【问题描述】:
class Photo:
    'Fields: size, pdate'
    def __init__(self, size, pdate):
        self.size = size
        self.pdate = pdate

def create_photo_name_dict(pdel):
    photo_dictionary = {}
    for photo in pdel:
        photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(photo[2:]).isoformat())
    return photo_dictionary

create_photo_name_dict([["DSC315.JPG",55,2011,11,13],["DSC316.JPG",53,2011,11,12]])

这会产生TypeError: an integer is required。有什么问题?

【问题讨论】:

    标签: python class dictionary


    【解决方案1】:

    datetime.date 需要一个整数作为其参数。使用 photo[2:] 您正在传递一个切片,它是一个列表。因此出现错误。

    为了解决这个问题,解压列表:

    photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(*photo[2:]).isoformat())
    

    这是一个例子:

    >>> datetime.date([2010,8, 7])
    
    Traceback (most recent call last):
      File "<pyshell#71>", line 1, in <module>
        datetime.date([2010,8, 7])
    TypeError: an integer is required
    >>> datetime.date(*[2010,8, 7])
    datetime.date(2010, 8, 7)
    

    【讨论】:

      【解决方案2】:
      photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(photo[2:]).isoformat())
      

      在这里,您在photo[0].. 中获取字符串。您需要使用int(photo[0]) 对其进行类型转换。

      同时检查您是否收到photo[0] int string 格式

      photo_dictionary[int(photo[0])] = Photo(photo[1],datetime.date(photo[2:]).isoformat())
      

      【讨论】:

        猜你喜欢
        • 2012-11-08
        • 1970-01-01
        • 2013-08-17
        • 2020-01-25
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 2015-02-15
        • 2019-03-11
        相关资源
        最近更新 更多