将SAS数字转换为python datetime

Chr*_*ris 5 python format datetime pandas

这可能是一个简单的解决方案,但我将如何转换SAS日期时间编号(自1960年1月1日以来的秒数.)pandas列中的一个值的示例是1716470000.

我试过了:

df['PyDatetime'] = pd.to_datetime(df,infer_datetime_format=True)
Run Code Online (Sandbox Code Playgroud)

我得到像'1970-01-01 00:00:01.725480'这样的数字

Pau*_*l H 6

你需要内置datetime模块:

import datetime
sastime = 1716470000
epoch = datetime.datetime(1960, 1, 1)
print(epoch + datetime.timedelta(seconds=sastime))
Run Code Online (Sandbox Code Playgroud)

这表现了:

datetime.datetime(2014, 5, 23, 13, 13, 20) # is this right?
Run Code Online (Sandbox Code Playgroud)

因此,如果您的数据框中包含一个名为的列sastime,您可以执行以下操作:

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))
) 
Run Code Online (Sandbox Code Playgroud)