简体   繁体   中英

TypeError: 'datetime.datetime' object is not callable

I have some Python code that iterates through all the days between two start dates. The start date is always November 1st and the end date is always May 31st. 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:

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. Can anyone tell me why this is?

Thanks

This is because you are having a variable called date that is shadowing imported 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM