简体   繁体   中英

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 . What is the problem?

datetime.date needs an integer as its parameters. With photo[2:] You are passing a slice, which is a list. 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]) .

Also Check whether you are getting photo[0] int in string format

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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