比较Python中的两个日期对象:TypeError:'datetime.date'和'method'实例之间不支持'<'

k88*_*k88 5 python datetime date

这不应该太难,但我似乎无法让它工作.我想在Python中比较两个datetime.date类型,但我不断收到类型错误:

from datetime import date  

class Vacancy(object):
    def __init__(self, date): #date is a datetime string of format 2017-13-03T00.00.000Z
        self.date = datetime.strptime(date[:-1], '%Y-%m-%dT%H:%M:%S.%f').date()

    def getDate(self):
         return self.date


all_objects = [o1, o2, o3, o4, ...] #contains objects of type Vacancy
for o in all_objects:
    earliestDate = date(2020, 1, 1) 
    if o.getDate() < earliestDate:
        earliestDate = o.getDate()

print(earliestDate)
Run Code Online (Sandbox Code Playgroud)

TypeError: '<' not supported between instances of 'datetime.date' and 'method'

这是没有意义的我,因为: print(type(earliestDate))print(type(o.getDate())) 两个给 <class 'datetime.date'>

我能做错什么?

编辑:为all_objects中的对象添加了类示例代码

EDIT2:正如你们许多人所指出的那样,确实缺少'()'.在我的实际代码中,我通过执行分配值的方法instad earliestDate = o.getDate.下次我会尝试对我的代码更加真实.感谢大家提供的见解,因为我确实来自Java,但我还没有完全理解Python.

And*_*zlo 9

TypeError应该给你你需要解决这个问题的所有信息.以下是解释它的方法:

TypeError: '<' not supported between instances of 'datetime.date' and 'method'
Run Code Online (Sandbox Code Playgroud)
  • 如您所知,这'<' not supported意味着您在使用<运算符时遇到错误.
  • 比较不起作用,因为您要比较的事情之一不是datetime.date实例.你也已经有了这个.
  • method类型是你会得到什么,如果你会使用o.getDate替代o.getDate().在Python中,您可以根据需要传递方法作为值,就像lambdas或函数一样.但是,在这种情况下,这不是您想要的,因此请确保您()在任何想要调用方法的地方使用它,即使它不接受任何参数.
  • 错误消息中类型的顺序也很有趣.这datetime.date到来之前method意味着日期是在左边侧和有问题的值在右侧边.在你的情况下,earliestDate持有一个method而不是一个datetime.date.
  • 现在我们知道这earliestDate是问题,它在哪里更新?earliestDate = date(2020, 1, 1)显然是约会,但怎么样earliestDate = o.getDate()?它正在使用parantheses,所以o.getDate()必须返回一个method.
  • 鉴于您的代码,Vacancy将始终self.date设置为日期,或将抛出异常(类似ValueError: time data 'xxx' does not match format '%Y-%m-%dT%H:%M:%S.%f').我猜你的代码看起来不同,初始化Vacancy是错误的.这是提供MCVE的好处:)