问题描述
我尝试过
In [16]: import datetime
In [17]: now = datetime.datetime.utcnow()
In [18]: isinstance(now, datetime.date)
Out[18]: True
In [19]: isinstance(now, datetime.datetime)
Out[19]: True
我期望的是第一个实例应返回False。
What I expected is that the first isinstance should return False. What happened?
推荐答案
由于 datetime
继承自 date
,每个 datetime
的实例也也是 date $ c的
实例$ c>,即您可以在任何使用 date
实例的地方使用 datetime
实例。这是面向对象编程中的。
Since datetime
inherits from date
, every instance of datetime
also is an instance of date
, i.e. you can use datetime
instances wherever you would use date
instances. This is a central concept in object-oriented programming.
要修改支票以执行所需的操作,可以使用 type(现在)为datetime专门测试
。或者,您可以使用 date
.date isinstance(现在,datetime.date)而不是isinstance(现在,datetime.datetime)$ c $显式排除
datetime
c>。
To modify the check to do what you want, you can test specifically for date
by using type(now) is datetime.date
. Or, you can explicitly exclude datetime
with isinstance(now, datetime.date) and not isinstance(now, datetime.datetime)
.
这篇关于如何检查变量是datetime.datetime还是datetime.date的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!