5

我被困住了。看来那一天正在某处被覆盖为 int 。但是哪里?day 在哪里变成 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
4

1 回答 1

15

.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文档中:

实例属性(只读):

date.year
介于MINYEARMAXYEAR包容之间。

date.month
介于 1 和 12 之间。

date.day
介于 1 和给定年份的给定月份的天数之间。

它被实现为数据描述符(如 a property)以使其只读,因此TypeError: 'getset_descriptor' object is not callable您看到了错误。

于 2013-04-08T18:07:23.913 回答