Python 和 Pandas 中的日期时间和时间戳相等

Datetime and Timestamp equality in Python and Pandas

我一直在研究日期时间和时间戳,但遇到了一些我无法理解的事情。

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 函数的替代方法,并且有效。这一定是 unique() 函数的一个怪癖。

您必须转换为 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 returns 一个 np 数组并且没有 numpy 当前理解 TimeStamp 的数据类型:Converting between datetime, Timestamp and datetime64