89

我尝试了一些明显的选择,但没有一个有效:

In [150]: x
Out[150]: datetime.date(2012, 9, 1)

In [151]: type(x)
Out[151]: datetime.date

In [152]: isinstance(x, datetime.date)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-152-9a298ea6fce5> in <module>()
----> 1 isinstance(x, datetime.date)

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

In [153]: x is datetime.date
Out[153]: False

In [154]: type(x) is datetime.date
Out[154]: False

这样做的正确方法是什么?

4

8 回答 8

140

我相信它在您的示例中不起作用的原因是您已经datetime像这样导入了:

from datetime import datetime

这会导致您看到的错误

In [30]: isinstance(x, datetime.date)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/<ipython-input-30-9a298ea6fce5> in <module>()
----> 1 isinstance(x, datetime.date)

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

如果您只是像这样导入:

import datetime

代码将如所有其他答案所示运行

In [31]: import datetime

In [32]: isinstance(x, datetime.date)
Out[32]: True

In [33]: 
于 2013-04-22T16:06:15.213 回答
17

正确的方法是

import datetime
isinstance(x, datetime.date)

当我在我的机器上尝试这个时,它工作正常。你需要看看为什么datetime.date不是一个类。你可能用别的东西掩盖它吗?还是没有正确引用它来进行导入?

于 2013-04-22T15:58:48.623 回答
14
import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True
于 2013-04-22T15:59:34.373 回答
12

根据文档classdate是 class 的父级datetime。在所有情况下,isinstance()方法都会给你。True如果你需要区分datetimedate应该检查类的名称

import datetime

datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False

当我对日期和日期与时间有不同的格式规则时,我遇到了这个问题

于 2018-11-27T08:38:55.443 回答
8

在 Python 3.8.4 中,可以检查 with 方法在检查 a是 a还是 aisinstance时会失败,因为两个检查都会给出.datetimedatedatetimeTrue

    >>> from datetime import datetime, date
    >>> mydatetime = datetime.now()
    >>> mydate = mydatetime.date()
    >>> isinstance(mydatetime, datetime)
    True
    >>> isinstance(mydatetime, date)
    True

这是因为它datetime是的子类,date正如在其他答案中所解释的那样:

派生类的实例也是基类的实例

因此,在区分datetime和时datetype应改为:

    >>> type(mydatetime) == date
    False
    >>> type(mydate) == date
    True
    >>> type(mydate) == datetime
    False
    >>> type(mydatetime) == datetime
    True
于 2021-08-11T14:10:07.287 回答
6

如果您现有的代码已经依赖from datetime import datetime,您也可以简单地导入date

from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)
于 2015-12-01T19:21:32.290 回答
3

在 Python 3.5 中,isinstance(x, date)对我有用:

>>> from datetime import date
>>> x = date(2012, 9, 1)
>>> type(x)
<class 'datetime.date'>
>>> isinstance(x, date)
True
>>> type(x) is date
True
于 2016-05-05T06:43:20.067 回答
0

如果您在测试中使用freezegun包,您可能需要进行更智能的 isinstance 检查,这与FakeDate和原始日期/日期时间在freeze_time上下文中运行良好:

def isinstance_date(value):
    """Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
    import datetime
    if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.today().date()) == type(value):
        return True
    else:
        return False


def isinstance_datetime(value):
    """Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
    import datetime
    if isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.now()) == type(value):
        return True
    else:
        return False

测试以验证实现

class TestDateUtils(TestCase):

    def setUp(self):
        self.date_orig = datetime.date(2000, 10, 10)
        self.datetime_orig = datetime.datetime(2000, 10, 10)

        with freeze_time('2001-01-01'):
            self.date_freezed = datetime.date(2002, 10, 10)
            self.datetime_freezed = datetime.datetime(2002, 10, 10)

    def test_isinstance_date(self):
        def check():
            self.assertTrue(isinstance_date(self.date_orig))
            self.assertTrue(isinstance_date(self.date_freezed))
            self.assertFalse(isinstance_date(self.datetime_orig))
            self.assertFalse(isinstance_date(self.datetime_freezed))
            self.assertFalse(isinstance_date(None))

        check()
        with freeze_time('2005-01-01'):
            check()

    def test_isinstance_datetime(self):
        def check():
            self.assertFalse(isinstance_datetime(self.date_orig))
            self.assertFalse(isinstance_datetime(self.date_freezed))
            self.assertTrue(isinstance_datetime(self.datetime_orig))
            self.assertTrue(isinstance_datetime(self.datetime_freezed))
            self.assertFalse(isinstance_datetime(None))

        check()
        with freeze_time('2005-01-01'):
            check()

于 2020-06-29T15:46:14.743 回答