Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SAS numeric to python datetime

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'

like image 600
Chris Avatar asked Nov 14 '14 05:11

Chris


1 Answers

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))
) 
like image 182
Paul H Avatar answered Sep 30 '22 09:09

Paul H