2013-04-08 110 views
3

我卡住了。看起來這一天似乎被某個地方的int所覆蓋。但是哪裏?一天成爲一個整數在哪裏?date.day()返回TypeError:'int'對象不可調用

from datetime import * 

start_date = date(1901, 1, 1) 
end_date = date(2000, 12, 31) 
sundays_on_1st = 0 

def daterange(start_date, end_date): 
    for n in range(int ((end_date - start_date).days)): 
     yield start_date + timedelta(n) 

for single_date in daterange(start_date, end_date): 

    # type(single_date) => <type 'datetime.date'> 
    # type(date.day()) => TypeError: 'getset_descriptor' object is not callable 
    # type(single_date.day()) => TypeError: 'int' object is not callable 
    # ಠ_ಠ 

    if single_date.day() == 1 and single_date.weekday() == 6: 
     sundays_on_1st += 1          

print sundays_on_1st 
+0

請*包含追蹤;如果沒有它,很難猜測錯誤可能在哪裏。 – 2013-04-08 18:06:31

回答

7

.day不是一種方法,你不需要調用它。只有.weekday()是一種方法。

if single_date.day == 1 and single_date.weekday() == 6: 
    sundays_on_1st += 1          

這只是正常:

>>> for single_date in daterange(start_date, end_date): 
...  if single_date.day == 1 and single_date.weekday() == 6: 
...   sundays_on_1st += 1 
... 
>>> print sundays_on_1st 
171 
>>> type(single_date.day) 
<type 'int'> 

datetime.date documentation

Instance attributes (read-only):

date.year
Between MINYEAR and MAXYEAR inclusive.

date.month
Between 1 and 12 inclusive.

date.day
Between 1 and the number of days in the given month of the given year.

它是作爲一個數據描述符(如property)來實現,使其只讀,因此您看到的TypeError: 'getset_descriptor' object is not callable錯誤。