I am trying to compile an old 2008 code .
import datetime
if isinstance(value, datetime.date):
But I got an error:
isinstance() arg 2 must be a class, type, or tuple of classes and types Python Executable: /usr/bin/python2.6 Python Version: 2.6.5
What am I missing?
I suspect you have imported the wrong datetime as in:
from datetime import datetime
instead use:
import datetime
I am running Python 2.7 and occasionally also ran into this error. Often simply checking the type will suffice if you do not need strict instance checking.
if id(type) and type(value) in (datetime.datetime, datetime.date):
#somecode
To clarify this more, you must be careful if datetime
is referring to the module from import datetime
or the datetime
class from from datetime import datetime
as both have a date
attribute.
In the first case, datetime.date
refers to the date class which can be used with isinstance
:
import datetime
type(datetime.date)
Out[13]: type
In the second case, the datetime.date
refers to the date method of the datetime class which cannot be used with isinstance
and hence the error.
from datetime import datetime
type(datetime.date)
Out[15]: method_descriptor
To help avoid errors like this it's best to explictly import and use the date class using from datetime import date
then use isinstance(value, date)
.
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.