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

這將產生TypeError: an integer is required 問題是什么?

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

在這里,您在photo[0]中得到字符串。.您需要使用int(photo[0])進行類型轉換。

另請檢查您是否正在以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