Python:如何检查对象是否为datetime.date类型?

时间:2013-04-22 15:56:22

标签: python datetime

我尝试了一些明显的选项,但没有一个可行:

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

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

8 个答案:

答案 0 :(得分:82)

我相信它在你的例子中不起作用的原因是你导入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]: 

答案 1 :(得分:9)

正确的方法是

import datetime
isinstance(x, datetime.date)

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

答案 2 :(得分:4)

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

答案 3 :(得分:2)

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

from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)

答案 4 :(得分:2)

在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

答案 5 :(得分:1)

根据documentationdate是类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

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

答案 6 :(得分:0)

如果您在测试中使用 freezegun 软件包,则可能需要进行更多的智能实例检查,该软件包与 FakeDate < / strong>和原始的 Date / Datetime 日期/日期时间)在具有Frozen_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()

答案 7 :(得分:0)

在 Python 3.8.4 中,可以检查带有 isinstance 的方法在检查 datetimedate 还是 datetime 时会失败,因为两者都检查会给True

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

这是因为 datetime is a subclass of dateas it is explained in this other answer:

<块引用>

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

因此,在区分datetimedate时,应该使用type来代替:

    >>> type(mydatetime) == date
    False
    >>> type(mydate) == date
    True
    >>> type(mydate) == datetime
    False
    >>> type(mydatetime) == datetime
    True