date.day()返回TypeError:'int'对象不可调用

时间:2013-04-08 18:05:20

标签: date datetime python-2.7 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

1 个答案:

答案 0 :(得分:8)

.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

  

实例属性(只读):

     

date.year
  在MINYEARMAXYEAR之间。

     

date.month
  在1到12之间。

     

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

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

相关问题