Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError when creating a date object

I'm trying to create a datetime.date object from integers, this is my code:

datetime.date(2011, 1, 1)

It gives me this error:

TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
like image 901
Alejandro Simkievich Avatar asked Dec 25 '22 08:12

Alejandro Simkievich


2 Answers

If you do the following, it'll work neatly:

>>> import datetime
>>> datetime.date(2011,1,1)
datetime.date(2011, 1, 1)

However, if you do this:

from datetime import datetime

and then

datetime.date(2011,1,1)

the method you're actually calling is datetime.datetime.date(2011,1,1), which will fail:

>>> datetime.datetime.date(2011,1,1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
like image 91
Aleksander Lidtke Avatar answered Dec 27 '22 12:12

Aleksander Lidtke


answer, based on the very generous contributions above.

The problem is that the datetime library includes a datetime class, which to the uninitiated sometimes is confusing.

To wrap up, if you do:

import datetime
datetime.date(2011, 1, 1)

you get

>>> datetime.date(2011, 1, 1)

Since you are using the date class of the datetime library. However, if you do

from datetime import datetime
datetime.date(2011, 1, 1)

you will get

>>>TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'

since you are (inadvertently) using the datetime class of the datetime library, which equates to:

datetime.datetime.date(2011, 1, 1)

and the datetime class of the datetime library has no date method

like image 44
Alejandro Simkievich Avatar answered Dec 27 '22 10:12

Alejandro Simkievich