Reputation: 139
So, for a long time now, I have been using code like the following in Python for version tracking:
...
import datetime
...
"""
Version tracking
"""
__version__ = 4.0
__dateV__ = datetime.date(2015, 5, 7)
...
Now, out of the blue, I get an error saying "TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'"
This has never happened before, and the documentation for the datetime module says that a "date" object should be initialized with year, month, and day arguments, which are all INTEGERS.
I have confirmed that I am using Python version 2.7.
Has anyone else seen this error? This is literally at the top of my code (right after all of the imports.) Please help.
Upvotes: 1
Views: 16294
Reputation: 3179
I think you are using `from datetime import *:
>>> from datetime import *
>>> date = datetime.date(2015, 5, 7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
Usefrom datetime import date
then:
>>> date = date(2015, 5, 7)
Upvotes: 1
Reputation: 139
Upon closer inspection, I have found that the root cause of the error was actually in one of my import statements.
One of my modules had an error in it, but for some reason that error was not caught until the line dateV = datetime.date(5, 7, 2015)
The datetime module was imported correctly, but the traceback sent me on a wild goose chase. Commenting out the imports of the faulty modules got rid of the error.
Upvotes: 0
Reputation: 25508
As the comments above have suggested, you've probably imported with
from datetime import datetime
That is, the name datetime
will refer to the class datetime
representing a date and time together (imported from the datetime
module, which, annoyingly, has the same name).
Then, date
is a method for retrieving the date-part of a datetime
object:
In [4]: my_date = datetime(2015,5,7,20,02,00)
In [5]: my_date.date()
In [6]: datetime.date(2015, 5, 7)
It doesn't take any arguments (see the source) apart from self
, so if you call it with one or more integer arguments, it complains:
In [7]: datetime.date(999)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-55d65eb13663> in <module>()
----> 1 datetime.date(999)
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
In this context, datetime.date
is the method of a datetime
object and doesn't know what to do with 999
. The following are equivalent:
In [8]: datetime.date(my_date)
Out[8]: datetime.date(2015, 5, 7)
In [9]: my_date.date()
Out[9]: datetime.date(2015, 5, 7)
If you import the datetime
module, you can do what you want because date
is also the name of a class (for representing dates without hours, minutes, etc) within this module:
In [1]: import datetime
In [2]: datetime.date(2015, 5, 7) # OK, returns a date object
Upvotes: 2