[英]Python isinstance() returning error with datetime.date
I am trying to compile an old 2008 code . 我正在尝试编译旧的2008代码 。
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
isinstance()arg 2必须是类和类型的类,类型或元组Python可执行文件:/usr/bin/python2.6 Python版本: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. 我正在运行Python 2.7,偶尔也会遇到此错误。 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. 为了更清楚地说明这一点,如果
datetime
指的是import datetime
的模块,或者datetime
类from datetime import datetime
,则必须小心,因为它们都有一个date
属性。
In the first case, datetime.date
refers to the date class which can be used with isinstance
: 在第一种情况下,
datetime.date
引用可与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. 在第二种情况下,
datetime.date
引用datetime类的date方法,该方法不能与isinstance
一起使用,因此也就是错误。
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)
. 为了帮助避免这样的错误,最好使用
from datetime import date
明确地导入和使用日期类from datetime import date
然后使用isinstance(value, date)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.