Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

python - convert numeric sas date to datetime in Pandas

I am using Pandas 0.18 and read_sas to load a sas7bdat dataset.

The dates in the Pandas dataframe appear as:

Out[56]: 
0    19411.0
1    19325.0
2    19325.0
3    19443.0
4    19778.0
Name: sas_date, dtype: float64

pd.to_datetime does not recognize this format. What should I do parse the date correctly?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this link,

[A] SAS date value is a value that represents the number of days between January 1, 1960, and a specified date

Therefore, if we convert the numbers to Pandas Timedeltas and add them to 1960-1-1 we can recover the date:

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')

yields

0   2013-02-22
1   2012-11-28
2   2012-11-28
3   2013-03-26
4   2014-02-24
dtype: datetime64[ns]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...