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.
本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的好处:)| 归档时间: |
|
| 查看次数: |
8601 次 |
| 最近记录: |