I recently had a need to convert from a long value stored as the offset from the Unix epoch (milliseconds) to a SAS datetime value. This is occuring more and more dealing with NoSQL and other datasets. This wasn’t a very easy thing to find, but it was easy enough to do. I’m sharing here in case anybody else might find it useful.
The code below:
- Reads a dataset with the numeric milliseconds value,
- Divides by 1000 (SAS is seconds, timestamps are milliseconds),
- Uses the INTNX function to add 10 years (SAS datetimes are based on 1960, not 1970) in days (between 1960 and 1970 there are 3 leap days. Using “dtyear” for “10” will only give you 2 leap days),
- And finally, the GMTOFF function to localize the SAS datetime value for the current system (Unix epoch values are always computed from GMT, SAS seconds are based from the current offset).
format sas_dt datetime19.;
sas_dt = intnx('dtday', millis/1000, 365*10+3, 's') + gmtoff();
And for those of you who are generating content in SAS for other systems to consume, here is the function performed in reverse (generates millisecond values from the SAS datetime):
format millis best15.;
millis = intnx('dtday', sas_dt - gmtoff(), -365*10+3, 's') * 1000;