Python – Convert 5 digit date to datetime from SAS date

Question:

I have a 5 digit date variable that was exported from SAS. I am having trouble converting it into a datetime format in Python. The variable is currently stored as an object.

Here is a background on SAS dates:

"The SAS System represents dates as the number of days since a reference date. The reference date, or date zero, used for SAS date values is 1 January 1960. Thus, for example, 3 February 1960 is represented by the SAS System as 33. The SAS date for 17 October 1991 is 11612."

Here are two examples:

Asked By: nillawafer

||

Answers:

Let’s try pd.to_datetime with specified origin and unit

df['out'] = pd.to_datetime(df['Date'], unit='D', origin='1960-01-01')
print(df)

    Date        out
0  21032 2017-08-01
1  16387 2004-11-12
2      0 1960-01-01
3     33 1960-02-03
4  11612 1991-10-17
Answered By: Ynjxsjmh

@Ynjxsjmh ‘s answer is better than mine, however you could retrieve the date you’re looking for by adding the deltatime between your ‘origin’ date and the input(integer of amount of days to add upon origin) :

import datetime

date = datetime.datetime(1960, 1, 1)    # Constant for SAS date

def SASdate(days:int):
    """
    Convert SAS integer to date
    """
    return date + datetime.timedelta(days = days)

print(SASdate(0))
Answered By: Fred