简体   繁体   English

datetime.date:TypeError:必须为整数。 为什么?

[英]datetime.date: TypeError: an integer is required. Why?

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]])

This produces TypeError: an integer is required . 这将产生TypeError: an integer is required What is the problem? 问题是什么?

datetime.date needs an integer as its parameters. datetime.date需要一个整数作为其参数。 With photo[2:] You are passing a slice, which is a list. 使用photo[2:]您正在传递一个切片,这是一个列表。 Hence the error. 因此,错误。

To solve this, unpack the list: 要解决此问题,请解压缩列表:

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

Here is an example: 这是一个例子:

>>> 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)
photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(photo[2:]).isoformat())

Here, you are getting string in photo[0] .. you need to typecast it using int(photo[0]) . 在这里,您在photo[0]中得到字符串。.您需要使用int(photo[0])进行类型转换。

Also Check whether you are getting photo[0] int in string format 另请检查您是否正在以string格式获取photo[0] int

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM