在Pandas中将数字sas日期转换为datetime

ℕʘʘ*_*ḆḽḘ 6 python sas pandas

我正在使用Pandas 0.18read_sas加载sas7bdat数据集.

Pandas数据框中的日期显示为:

Out[56]: 
0    19411.0
1    19325.0
2    19325.0
3    19443.0
4    19778.0
Name: sas_date, dtype: float64
Run Code Online (Sandbox Code Playgroud)

pd.to_datetime无法识别此格式.我该怎么办才能正确解析日期?

谢谢!

unu*_*tbu 16

根据这个链接,

[A] SAS日期值是表示1960年1月1日和指定日期之间的天数的值

因此,如果我们将数字转换为Pandas Timedeltas并将其添加到 1960-1-1我们可以恢复日期:

import numpy as np
import pandas as pd

ser = pd.Series([19411.0, 19325.0, 19325.0, 19443.0, 19778.0])
ser = pd.to_timedelta(ser, unit='D') + pd.Timestamp('1960-1-1')
Run Code Online (Sandbox Code Playgroud)

产量

0   2013-02-22
1   2012-11-28
2   2012-11-28
3   2013-03-26
4   2014-02-24
dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)