簡體   English   中英

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()函數的怪癖。

您必須轉換為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當前可以理解TimeStamp在datetime,Timestamp和datetime64之間轉換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM