简体   繁体   English

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

[英]Comparing two date objects in Python: TypeError: '<' not supported between instances of 'datetime.date' and 'method'

This shouldn't be too difficult but I can't seem to get it to work. 这不应该太难,但我似乎无法让它工作。 I want to compare two datetime.date types in Python but I keep getting a Type Error: 我想在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)

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

Which doesn't make sense to me because: print(type(earliestDate)) and print(type(o.getDate())) both give <class 'datetime.date'> 这对我没有意义,因为: print(type(earliestDate))print(type(o.getDate()))都给<class 'datetime.date'> print(type(o.getDate())) <class 'datetime.date'>

What could I be doing wrong? 我能做错什么?

EDIT: added class sample code for the objects in all_objects 编辑:为all_objects中的对象添加了类示例代码

EDIT2: As many of you pointed out it is indeed a missing '()'. EDIT2:正如你们许多人所指出的那样,确实缺少'()'。 In my actual code I was assigning the method instad of the value by doing earliestDate = o.getDate . 在我的实际代码中,我通过执行earliestDate = o.getDate分配值的方法earliestDate = o.getDate Next time I'll try to be more truthful to my code. 下次我会尝试对我的代码更加真实。 Thank you all for the insight you provided as I indeed come from Java and I don't fully comprehend Python yet. 感谢大家提供的见解,因为我确实来自Java,但我还没有完全理解Python。

The TypeError should give you all information you need to solve this problem. TypeError应该为您提供解决此问题所需的所有信息。 Here's how to interpret it: 以下是解释它的方法:

TypeError: '<' not supported between instances of 'datetime.date' and 'method'
  • The '<' not supported means that you got the error when using the < operator, as you already know. '<' not supported表示您在使用<运算符时遇到错误,如您所知。
  • The comparison doesn't work because one of the things you are comparing is not a datetime.date instance. 比较不起作用,因为您要比较的事情之一不是datetime.date实例。 You already got this, too. 你也已经有了这个。
  • The method type is what you get if you would use o.getDate instead of o.getDate() . 如果使用o.getDate而不是o.getDate()o.getDate()获得method类型。 In Python you can pass around methods as values if you like, just like lambdas or functions. 在Python中,您可以根据需要传递方法作为值,就像lambdas或函数一样。 This is not what you want in this case however, so make sure you use () everywhere you want to call a method, even if it doesn't take any arguments. 但是,在这种情况下,这不是您想要的,因此请确保在想要调用方法的任何地方使用() ,即使它不接受任何参数。
  • The order of the types in the error message is also interesting. 错误消息中类型的顺序也很有趣。 That datetime.date comes before method mean that the date was on the left side and the problematic value was on the right side. datetime.date出现在method之前意味着日期在左侧 ,有问题的值在右侧 In your case, the earliestDate is holding a method instead of a datetime.date . 在您的情况下, earliestDate持有method而不是datetime.date
  • Now that we know that earliestDate is the problem, where is it updated? 现在我们知道earliestDate是问题,它在哪里更新? earliestDate = date(2020, 1, 1) is clearly a date, but how about earliestDate = o.getDate() ? earliestDate = date(2020, 1, 1) earliestDate = o.getDate()显然是一个日期,但是earliestDate = o.getDate()怎么样? It's using parentheses, so o.getDate() must be returning a method . 它使用括号,因此o.getDate()必须返回一个method
  • Given your code, the Vacancy will always have self.date set to a date, or an exception will be thrown (something like ValueError: time data 'xxx' does not match format '%Y-%m-%dT%H:%M:%S.%f' ). 鉴于您的代码, Vacancy将始终将self.date设置为日期,否则将抛出异常(类似于ValueError: time data 'xxx' does not match format '%Y-%m-%dT%H:%M:%S.%f' )。 I'm guessing your code looks different and the initialization for Vacancy is wrong somehow. 我猜你的代码看起来不一样,并且Vacancy的初始化在某种程度上是错误的。 This is the benefit of providing a MCVE :) 这是提供MCVE的好处:)

You overwritten the definition of date, try this (maintaining the datetime namespace with an alias: dt). 你覆盖了date的定义,试试这个(用别名维护datetime命名空间:dt)。 A good practice would be to not name local or member variables with the same name of functions and objects of the libraries you import (you imported date from datetime and then use date as the argument of the init). 一个好的做法是不要使用相同名称的函数和导入的库的对象来命名本地或成员变量(从datetime导入日期,然后使用date作为init的参数)。

import datetime as dt   

class Vacancy(object):
    def __init__(self, date):
        self.date = date

    def getDate(self):
         return self.date


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

print(earliestDate)

An extra observation is that in python there is no need of defining getters and setters, since the variables are public. 另外一个观察是,在python中不需要定义getter和setter,因为变量是公共的。 It is better if you just: 如果你只是:

import datetime as dt   

class Vacancy(object):
    def __init__(self, date):
        self.date = date

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

And if you want to be sure the date member variable is not modified, you can do something like this: 如果您想确保未修改日期成员变量,您可以执行以下操作:

class Vacancy(object):
    def __init__(self, date):
        self.date = date

    def getMinDate(self, other_date):
        if self.date < other_date:
            return dt.date(self.date)
        else:
            return other_date

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:“datetime.date”和“str”的实例之间不支持“&gt;” - TypeError: '>' not supported between instances of 'datetime.date' and 'str' TypeError: '>=' 在 'datetime.date' 和 'str' 的实例之间不被支持 - TypeError: '>=' not supported between instances of 'datetime.date' and 'str' '>' 在 'type' 和 'datetime.date' 的实例之间不受支持 - '>' not supported between instances of 'type' and 'datetime.date' Django List Comprehension-比较日期时间对象时遇到问题。 TypeError:不可排序的类型:datetime.date()&lt;= str() - Django List Comprehension - Trouble Comparing Datetime Objects. TypeError: unorderable types: datetime.date() <= str() python,datetime.date:两天之间的差异 - python, datetime.date: difference between two days TypeError:strptime()参数1必须是str,而不是datetime.date Python - TypeError: strptime() argument 1 must be str, not datetime.date Python Python datetime.date issue TypeError: an integer is required - Python datetime.date issue TypeError: an integer is required TypeError: 'datetime.datetime' 对象的描述符 'date' 不适用于 'datetime.date' object - TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object 计算两个datetime.date()日期之间的时差,以年和月为单位 - calculate the difference between two datetime.date() dates in years and months 尝试获取最小日期并获取 TypeError: &#39;&lt;&#39; 在 &#39;datetime.datetime&#39; 和 &#39;int&#39; 的实例之间不支持 - Trying to get the minimum date and getting TypeError: '<' not supported between instances of 'datetime.datetime' and 'int'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM