TypeError when creating a date object

I am trying to create an object datetime.datefrom integers, this is my code:

datetime.date(2011, 1, 1)

This gives me this error:

TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
+4
source share
5 answers

If you do the following, it will 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 that you are actually calling is datetime.datetime.date(2011,1,1)one that will not be executed:

>>> 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'
+4
source

based on the very generous contributions above.

The problem is that the datetime library includes the datetime class, which is sometimes confused for the uninitiated.

Finish if you run:

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

You get

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

datetime. ,

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

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

() datetime datetime, :

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

datetime datetime

+3

Just use the correct importone and you will install:

>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2016, 3, 4)
>>> date(2016, 3, 4)
datetime.date(2016, 3, 4)
+1
source

An error may occur due to yours import statement.

Change it:

from datetime import datetime

To:

import datetime
+1
source
>>> from datetime import datetime
>>> date = datetime(year=2011,month=1,day=1)
>>> print date
2011-01-01 00:00:00
>>> 

White Papers: datetimeObjects

+1
source

All Articles