我對使用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不正確解釋異常日期?
完美。感謝解決方案和其他推理。 – user1718097