代码之家  ›  专栏  ›  技术社区  ›  Min

在python2.7中比较timestamp和datetime64时的奇怪行为

  •  4
  • Min  · 技术社区  · 8 年前

    是否有人遇到类似的情况,如下面所述,如果我们 a 是一个 Timestamp , b 成为 datetime64 ,然后比较 a < b 很好,但是 b < a 返回错误。

    如果 可以与 ,我想我们应该能够比较另一种方式?

    例如(python 2.7):

    >>> a
    Timestamp('2013-03-24 05:32:00')
    >>> b
    numpy.datetime64('2013-03-23T05:33:00.000000000')
    >>> a < b
    False
    >>> b < a
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "pandas\_libs\tslib.pyx", line 1080, in pandas._libs.tslib._Timestamp.__richcmp__ (pandas\_libs\tslib.c:20281)
    TypeError: Cannot compare type 'Timestamp' with type 'long'
    

    非常感谢!

    1 回复  |  直到 8 年前
        1
  •  1
  •   gyx-hh    8 年前

    pandas numpy b<a

    class TestCom(int):
        def __init__(self, a):
        self.value = a
    
        def __gt__(self, other):
        print('TestComp __gt__ called')
        return True
    
        def __eq__(self, other):
        return self.a == other
    

    __gt__ < __eq__ ==

    a = TestCom(9)
    print(a)
    # Output: 9
    
    # my def of __ge__
    a > 100
    
    # Ouput: TestComp __gt__ called
    # True
    
    a > '100'
    # Ouput: TestComp __gt__ called
    # True
    
    '100' < a
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-486-8aee1b1d2500> in <module>()
          1 # this will not use my def of __ge__
    ----> 2 '100' > a
    
    TypeError: '>' not supported between instances of 'str' and 'TestCom'
    

    timestamps_sourceCode pandas.Timestamp

    pd.Timestamp np.datetime64 Timestamp.__richcmp__

    # we can do the following to have a comparison of say b > a
    # this converts a to np.datetime64 - .asm8 is equivalent to .to_datetime64()
    b > a.asm8
    
    # or we can confert b to datetime64[ms]
    b.astype('datetime64[ms]') > a
    
    # or convert to timestamp
    pd.to_datetime(b) > a
    

    nanoseconds

    a = pd.Timestamp('2013-03-24 05:32:00.00000001')
    a.nanosecond   # returns 10
    # doing the comparison again where they're both ns still fails
    b < a
    

    !=

    a = pd.Timestamp('2013-03-24 05:32:00.00000000')
    b = np.datetime64('2013-03-24 05:32:00.00000000', 'ns')
    
    b == a  # returns False
    
    a == b  # returns True
    

    False True

    nanosecond 0.23.0 pd.Timestamp('2013-03-23T05:33:00.000000022', unit='ns') ns

    SO_Datetime Timestamp datetime _compare_outside_nanorange

    SO int64

    1 > a
    a > 1
    

    Cannot compare type 'Timestamp' with type 'int'

    b > a int np.greater() np.greater ufunc_docs

    a == b b == a b Flase

    123 == '123'