Convert SAS numeric to python datetime

白昼怎懂夜的黑 提交于 2019-12-23 10:58:11

问题


This is probably a simple solution, but how would I go about converting a SAS datetime number (number of seconds since 1/1/1960.) An example of one of the values inside of the pandas column is 1716470000.

I tried:

df['PyDatetime'] = pd.to_datetime(df,infer_datetime_format=True)

and I get numbers like '1970-01-01 00:00:01.725480'


回答1:


You'll need the built-in datetime module:

import datetime
sastime = 1716470000
epoch = datetime.datetime(1960, 1, 1)
print(epoch + datetime.timedelta(seconds=sastime))

Which shows:

datetime.datetime(2014, 5, 23, 13, 13, 20) # is this right?

So if you have a dataframe with a column called sastime, you could do:

epoch = datetime.datetime(1960, 1, 1)
# cast -s- to python int in case it's a string or a numpy.int
df['datetime'] = df['sastime'].apply(
    lambda s: epoch + datetime.timedelta(seconds=int(s))
) 


来源:https://stackoverflow.com/questions/26923564/convert-sas-numeric-to-python-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!