2016-02-14 58 views
6

我對使用pymssql查詢並讀入Pandas數據框的數據庫擁有隻讀訪問權限。其中一個變量包含日期,其中一些日期爲0001年1月1日午夜(即0001-01-01 00:00:00.0000000)。我不知道爲什麼應該包含這些日期 - 據我所知,它們不被SQL Server識別爲有效日期,它們可能是由於一些默認的數據輸入。儘管如此,我必須與之合作。如何防止將pandas.to_datetime()函數從0001-01-01轉換爲2001-01-01

import numpy as np 
import pandas as pd 

tempDF = pd.DataFrame({ 'id': [0,1,2,3,4], 
         'date': ['0001-01-01 00:00:00.0000000', 
           '2015-05-22 00:00:00.0000000', 
           '0001-01-01 00:00:00.0000000', 
           '2015-05-06 00:00:00.0000000', 
           '2015-05-03 00:00:00.0000000']}) 

數據框的樣子:

print(tempDF) 
          date id 
0 0001-01-01 00:00:00.0000000 0 
1 2015-05-22 00:00:00.0000000 1 
2 0001-01-01 00:00:00.0000000 2 
3 2015-05-06 00:00:00.0000000 3 
4 2015-05-03 00:00:00.0000000 4 

...有以下dtypes:

print(tempDF.dtypes) 

date object 
id  int64 
dtype: object 
print(tempDF.dtypes) 

不過,我經常轉換日期這可以如下重建爲一個數據幀字段在數據幀中以日期時間格式使用:

tempDF['date'] = pd.to_datetime(tempDF['date']) 

但是,偶然發現0001-01-01的日期已轉換爲2001-01-01。

print(tempDF) 

     date id 
0 2001-01-01 0 
1 2015-05-22 1 
2 2001-01-01 2 
3 2015-05-06 3 
4 2015-05-03 4 

我意識到原始數據庫中的日期不正確,因爲SQL Server沒有將0001-01-01視爲有效日期。但至少在0001-01-01格式中,這些缺失數據很容易在我的Pandas數據框中識別。但是,當pandas.to_datetime()更改這些日期以使它們位於可行範圍內時,很容易錯過這些異常值。

如何確保pd.to_datetime不正確解釋異常日期?

回答

4

如果你提供了一個format,這些日期將不被認可:

In [92]: pd.to_datetime(tempDF['date'], format="%Y-%m-%d %H:%M:%S.%f", errors='coerce') 
Out[92]: 
0   NaT 
1 2015-05-22 
2   NaT 
3 2015-05-06 
4 2015-05-03 
Name: date, dtype: datetime64[ns] 

默認情況下它會出錯,但通過傳遞errors='coerce',它們被轉換NAT的值(coerce=True老年大熊貓版本)。

原因大熊貓將這些「0001-01-01」追溯到「2001-01-01」,而不提供format,是因爲這是dateutil行爲:

In [32]: import dateutil 

In [33]: dateutil.parser.parse("0001-01-01") 
Out[33]: datetime.datetime(2001, 1, 1, 0, 0) 
+0

完美。感謝解決方案和其他推理。 – user1718097