python - 在 python 中比较日期,== 有效但 <= 产生错误

标签 python python-3.x datetime

我正在尝试比较两个日期。此代码有效:

import datetime

todays_date = datetime.date.today()

date1 = datetime.date(2006, 3, 15)
date2 = datetime.date(2009, 4, 30)

print(date1 != date2)
print(date1 == 0)

它产生:

True
False

这些代码不起作用,我不知道为什么:

import datetime

todays_date = datetime.date.today()

date1 = datetime.date(2006, 3, 15)
date2 = datetime.date(2009, 4, 30)

print(date1 != date2)
print(date1 >= 0)

它产生这个错误:

File 'datetime.py', Line 363: AttributeError: 'int' object has no attribute '__name__'

请注意,我只是将==更改为>=,为什么相等比较的结果是TrueFalse,而大于比较会导致错误?

如有任何帮助,我将不胜感激!

最佳答案

长话短说

这是因为比较方法是如何定义的。


为什么 `==` 是可比较的,而 `>=` 不在 `time` 对象和类型 `int` 之间:

这是 source code 的副本对于 time 对象:

def __eq__(self, other):
    if isinstance(other, time):
        return self._cmp(other, allow_mixed=True) == 0
    else:
        return False

def __ge__(self, other):
    if isinstance(other, time):
        return self._cmp(other) >= 0
    else:
        _cmperror(self, other)

__eq__ 在不是另一个 time 实例时返回 False,而 __ge__ 调用 _cmperror,定义如下:

def _cmperror(x, y):
    raise TypeError("can't compare '%s' to '%s'" % (
                    type(x).__name__, type(y).__name__))

非常重要的编辑

虽然这个答案已经得到了一些积极的分数,但我没有看到你的问题,你使用了 date 对象,而不是 time 对象。

为什么 `==` 是可比较的,而 `>=` 不在 `date` 对象和类型 `int` 之间:

首先,date 对象与time 对象不同,它们对于__eq____ge__ 的实现是一样的>。它们实际上都返回 NotImplemented,因此 date 对象的方法没有什么特别之处:

def __eq__(self, other):
    if isinstance(other, date):
        return self._cmp(other) == 0
    return NotImplemented

def __ge__(self, other):
    if isinstance(other, date):
        return self._cmp(other) >= 0
    return NotImplemented

然而,不同之处在于 int__eq__ 与其他方法的比较。 int 返回 False 当一个对象对于 __eq__NotImplemented 对于 __ge__< 具有不可比较的类型时.

date 返回的 NotImplemented 将导致对 int 方法的回退。由于 int 始终是相等可比较的,因此 date == 0 不会导致错误。

这是一个例子:

class LikeDate:
    def __eq__(self, other):
         if isinstance(other, LikeDate):
             return True
         else:
              return NotImplemented

    def __ge__(self, other):
         if isinstance(other, LikeDate):
             return True
         else:
              return NotImplemented

class LikeInt:
    def __eq__(self, other):
         if isinstance(other, LikeInt):
             return True
         else:
             return False

    def __ge__(self, other):
         if isinstance(other, LikeInt):
             return True
         else:
              return NotImplemented

a = LikeDate()
b = LikeInt()
print(a == b) # False
print(a == 0) # False, because int provides an __eq__ method that returns False
print(a >= 0) # Error, because nether LikeDate nor int provides a definite comparison for __ge__
print(a >= b) # Error, because neither objects provide a comparable __ge__

You can run this example here.


如果您不知道return NotImplemented 是什么,这里有一个简短的解释和来自 doc 的引述:

When a binary [ ( __eq__, __ge__ ...) ] (or in-place) method returns NotImplemented the interpreter will try the reflected operation on the other type (or some other fallback, depending on the operator). If all attempts return NotImplemented, the interpreter will raise an appropriate exception. Incorrectly returning NotImplemented will result in a misleading error message or the NotImplemented value being returned to Python code.

当从二进制方法返回 NotImplemented 时,它表示二进制方法无法将自身与目标的类型进行比较。二元方法的结果将取决于其他对象的二元方法。如果两个对象都返回 NotImplemented,则会引发错误。

关于python - 在 python 中比较日期,== 有效但 <= 产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071339/

相关文章:

python - 无法访问Locust WebInterface "ERR_CONNECTION_REFUSED"

python - 如何从 Python 脚本中列出 Python 可用的所有包/模块?

python-3.x - ctypes 不释放字符串缓冲区吗?

python - 正在构造 key :Value pair from list comprehension in Python

python - 如何获取所有字典值(字符串)的总长度

python - 从电子邮件中解析带有时区的日期?

python - 找不到元素 Selenium Python

python - 需要 Openshift、python、mongodb 和 cron 指导

php - 在 PHP 中执行日期时间相关操作

python - 格式化 Pandas 数据框索引日期