[英]TypeError: 'datetime.datetime' object is not callable
I have some Python code that iterates through all the days between two start dates. 我有一些Python代码遍历两个开始日期之间的所有日子。 The start date is always November 1st and the end date is always May 31st. 开始日期始终是11月1日,结束日期始终是5月31日。 However, the code iterates through years. 但是,代码会循环使用多年。 My code is as so: 我的代码如下:
import time
from datetime import datetime
from datetime import date, timedelta as td
list1 = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
list2 = [2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014]
for x, y in zip(list1, list2):
print "list1 - " + str(x)
print "list2 - " + str(y)
d1 = date(x,11,01)
d2 = date(y,5,31)
delta = d2 - d1
for i in range(delta.days + 1):
time1 = str(d1 + td(days=i))
time2 = time1.split("-", 1)[0]
time3 = time1.split("-", -1)[1]
time4 = time1.rsplit("-", 1)[-1]
time2 = int(time2)
time3 = int(time3)
time4 = int(time4)
date = datetime(year=time2, month=time3, day=time4)
...some processing here...
This code works fine until the first cycle is completed. 此代码正常工作,直到第一个循环完成。 It then prints the next two values of 'list1' and 'list2' as 2001 and 2002 to the log, before producing the following error: 然后,在生成以下错误之前,它将“list1”和“list2”的下两个值作为2001和2002打印到日志中:
Traceback (most recent call last):
File "C:\Python27\newtets\newtets\spiders\test3.py", line 17, in <module>
d1 = date(x,11,01)
TypeError: 'datetime.datetime' object is not callable
It doesn't seem to be resolving the year assigned to the variable 'x' on this second pass through. 它似乎没有解决在第二次传递中分配给变量'x'的年份。 Can anyone tell me why this is? 谁能告诉我为什么会这样?
Thanks 谢谢
This is because you are having a variable called date
that is shadowing imported datetime.date
. 这是因为您有一个名为date
的变量,该变量将导入datetime.date
。 Use a different variable name. 使用其他变量名称。
Demo: 演示:
>>> from datetime import date, datetime
>>> date(01,11,01)
datetime.date(1, 11, 1)
>>> date = datetime(year=2014, month=1, day=2)
>>> date(01,11,01)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'datetime.datetime' object is not callable
I think that the following line: 我认为以下几行:
date = datetime(year=time2, month=time3, day=time4)
is the issue. 是问题。 Here, you are re-defining date to have a different value (that can't be called) to the date class (which could be). 在这里,您要重新定义日期 ,以便为日期类(可能是)提供不同的值(无法调用)。
On the 'second pass through', it gets to: 在'第二次通过',它到达:
d1 = date(x,11,01)
and date isn't what it used to be (it can't be called), and so you get the error. 和日期不是以前的(它不能被调用),所以你得到错误。
Maybe change variable name to be something else, eg dte? 也许将变量名称更改为其他内容,例如dte?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.