【问题标题】:Datetime and Timestamp equality in Python and PandasPython 和 Pandas 中的日期时间和时间戳相等
【发布时间】:2015-07-17 16:06:15
【问题描述】:

我一直在玩弄日期时间和时间戳,但遇到了一些我无法理解的东西。

import pandas as pd
import datetime

year_month = pd.DataFrame({'year':[2001,2002,2003], 'month':[1,2,3]})
year_month['date'] = [datetime.datetime.strptime(str(y) + str(m) + '1', '%Y%m%d') for y,m in zip(year_month['year'], year_month['month'])]

>>> year_month
  month  year       date
0     1  2001 2001-01-01
1     2  2002 2002-02-01
2     3  2003 2003-03-01

我认为独特的功能正在对正在以某种方式改变它们的时间戳做一些事情:

first_date = year_month['date'].unique()[0]

>>> first_date == year_month['date'][0]
False

事实上:

>>> year_month['date'].unique()
array(['2000-12-31T16:00:00.000000000-0800',
       '2002-01-31T16:00:00.000000000-0800',
       '2003-02-28T16:00:00.000000000-0800'], dtype='datetime64[ns]')

我怀疑函数下面存在某种时区差异,但我无法弄清楚。

编辑

我刚刚检查了 python 命令 list(set()) 作为唯一函数的替代方法,并且有效。这一定是 unique() 函数的一个怪癖。

【问题讨论】:

    标签: python datetime pandas timestamp equality


    【解决方案1】:

    您必须转换为 datetime64 才能比较:

    In [12]:
    first_date == year_month['date'][0].to_datetime64()
    Out[12]:
    
    True
    

    这是因为unique 已将dtype 转换为datetime64

    In [6]:    
    first_date = year_month['date'].unique()[0]
    first_date
    
    Out[6]:
    numpy.datetime64('2001-01-01T00:00:00.000000000+0000')
    

    我认为是因为unique 返回了一个 np 数组,并且目前没有 numpy 可以理解的 dtype TimeStampConverting between datetime, Timestamp and datetime64

    【讨论】:

    • 我认为问题在于 numpy 没有兼容的 dtype,因此它被转换为 datetime64
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2020-08-20
    • 2013-06-16
    相关资源
    最近更新 更多