【问题标题】:date.day() returns TypeError: 'int' object is not callabledate.day() 返回 TypeError: 'int' object is not callable
【发布时间】:2013-03-30 22:26:41
【问题描述】:

我被困住了。看来那一天正在某处被覆盖为 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

【问题讨论】:

  • 包括回溯;如果没有它,很难猜测错误可能出在哪里。

标签: date datetime python-2.7 typeerror


【解决方案1】:

.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 错误。

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2017-04-06
    • 2015-01-05
    • 2018-07-23
    • 2018-03-31
    • 2018-04-14
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多