How to convert a Unix datetime to a SAS datetime

timeI watched with wonder as each of my daughters learned how to "tell time." Early in their primary school careers, they brought home worksheets that featured clock faces with big-hand/little-hand configurations that they had to decipher, and exercises that asked them to draw the hands as they should appear given a specific elapsed time. Now my daughters have digital watches, and have even adopted my habit of wearing them with the face on the underside of the wrist and setting the display to 24-hour time -- which serves to confound their friends.

But, to my disappointment, their school has failed to teach my daughters how to read a SAS datetime value, or even the more ubiquitous Unix (POSIX) datetime value. As a parent of the 21st century, I feel it is my duty to fill this gap in their education.

First, let's review how these datetime values are represented:

  • A SAS datetime value is the number of seconds that have elapsed since midnight of January 1, 1960 (01JAN1960:00:00:00).
  • A Unix (or POSIX) datetime value is the number of seconds* that have elapsed since midnight of January 1, 1970 (01JAN1970:00:00:00).

Conversion from Unix to SAS representation is simple math:

/* Number of seconds between 01JAN1960 and 01JAN1970: 315619200 */
sasDT = unixDT + 315619200;

Having trouble remembering that 9-digit constant? Then you can get SAS to infer that part for you and use the dhms() function:

/* DHMS function calculates datetime when you provide values for */
/*    date, hour, minute, and seconds                            */
/* In this case, "seconds" is a very high value!                 */
sasDT = dhms('01jan1970'd, 0, 0, unixDT);

Raw Unix times are often expressed as UTC, and you might prefer to show local times in your SAS reporting. That's a simple calculation with the (undocumented) gmtoff() function:

/* Convert from UTC to local time using GMTOFF */
sasDT = dhms('01jan1970'd,0,0, unixDT + gmtoff());

Update: Bruno told me that TZONEOFF is an official SAS function in SAS 9.4! See the comments for more details how you can use it instead of GMTOFF.

I have one more variation that I use every day. I have a project that reports against a database that stores transaction times in milliseconds instead of seconds. (This uses the database's intrinsic int8 or BIGINT type.) SAS datetime values can represent fractions of seconds, so this conversion simply requires that I divide by 1000. I can use a different SAS datetime format to see the precision (if that's what I want, though it's usually not).

/* for more precision */
format sasDT datetime22.3; 
/* mlliseconds from transaction database */
unixDTms = 1429193343362;
sasDT_ms = dhms('01jan1970'd,0,0, unixDTms/1000);
/* result: 16APR2015:14:09:03.362 */

Here's a complete program that you can experiment with:

data t;
  format sasDT_const 
    sasDT_dhms 
    sasDT_local datetime20.;
 
  /* for more precision */
  format sasDT_ms datetime22.3;
 
  /* Unix test datetime of 16APR2015:14:09:03 UTC */
  unixDT =   1429193343;
 
  /* mlliseconds from transaction database */
  unixDTms = 1429193343362;
 
  /* Number of seconds between 01JAN1960 and 01JAN1970: 315619200 */
  sasDT_const = unixDT + 315619200;
 
  /* DHMS function calculates datetime given values for */
  /*    date, hour, minute, and seconds                 */
  /* In this case, "seconds" is a very high value!      */
  sasDT_dhms = dhms('01jan1970'd,0,0,unixDT);
 
  /* converting a value from milliseconds */
  sasDT_ms = dhms('01jan1970'd,0,0,unixDTms/1000);
 
  /* Convert from UTC to local time using GMTOFF */
  /* use TZONEOFF function in 9.4! */
  sasDT_local = dhms('01jan1970'd,0,0,unixDT + gmtoff()); 
run;

Sample output from this program (which I ran from my EDT timezone):
time_out
* I intentionally avoided any discussion of leap seconds that go along with UTC, but you can learn more about that here.

See also

Read a Microsoft datetime value into a SAS datetime value

Post a Comment

How to compare SAS programs in SAS Enterprise Guide

Copy/paste is my favorite method for creating new SAS programs. In my work projects, I maintain a sort of genealogy of SAS programs, because the DNA of one program can be used to spawn many other SAS programs as its progeny. When things (inevitably) aren't working as I intend in one of these next-generation programs, I find that I need to compare that program against the original to see what I've missed.

My file-comparison tool of choice is WinMerge. It's free and easy to install and use. That's why I'm really pleased with the new Compare Programs feature in SAS Enterprise Guide 7.1.

Here is how you set it up.

1. Install a file comparison tool.

I like WinMerge. But some of my colleagues prefer Beyond Compare or KDiff. Your choice! Most of these tools can integrate with your file system so that you can compare any two files from Windows Explorer. They also integrate with source control systems, if you use those (Git, Subversion, etc.).

2. Set your File Comparison options in SAS Enterprise Guide

Select Tools->Options, then the File Comparison tab. Check "Use custom file comparison tool" and then select your tool of choice. There are built-in presets for the three comparison tools that I mentioned, or you can go "off road" and select your favorite with "Other".

Select your DIFF tool

3. Select the two files that you want to compare

In the Project Tree or Process Flow, you can select multiple programs by using the standard Ctrl+Click sequence or by "rubber banding" a selection with the mouse (Process Flow only). When you have exactly two programs selected, right-click and select Compare.

Compare programs menu
The comparison tool launches with the contents of each program loaded for comparison. Here's what mine looks like:

Code compare in action
Some additional notes:

  • The content you see in the comparison tool is a copy of your program. Therefore, if you use the comparison tool to make changes, these won't be reflected in your SAS Enterprise Guide project. Of course, you can copy the changed content to the Windows clipboard and paste it into the SAS Enterprise Guide program editor.
  • You can do more with file comparison when using the Program History feature, which I introduced in this blog post about new programming features in SAS Enterprise Guide 7.1.
Post a Comment

Project Reviewer task and Copy Files task: refreshed for v7.1

Two popular SAS custom tasks have recently been updated for SAS Enterprise Guide 7.1. Most custom tasks that I've shared will work without modification across releases, but these two required a special rebuild due to some internal product API changes.

The Project Reviewer task allows you to see a detail view of the tasks/programs within your SAS Enterprise Guide process flows. The listing shows the task names and types, when they were added to the project and last modified, and how much time they take to run. You can also create a SAS-based ODS report from the data, which is a great way to use SAS Enterprise Guide to report on your SAS Enterprise Guide project. (Wow, that's so meta!)

projectrev71
Download Project Reviewer: See this blog post for more information and download link

The Copy Files task is used to move files from your local PC to your SAS session, or from your SAS session to your local PC. This allows you to capture these file transfer steps within your process flow so that they are repeatable. The task supports the use of macro variables and wildcards, which gives you lots of flexibility when designing a process in which the file names and quantities are subject to change.

Copy Files task
Download Copy Files: See this blog post for more information and download link

If you use these tasks (or other custom tasks) and find them useful, please leave a comment! I love to hear how the tasks are being used. And sometimes useful custom tasks find their way into the actual product in a future release. Your feedback is important to help to make that happen.

Other related articles

Post a Comment

Can you learn how to create custom tasks?

To develop a custom task for use in SAS Enterprise Guide (or SAS Add-In for Microsoft Office), you need a few things:

  • A working knowledge of SAS and SAS Enterprise Guide
  • Microsoft Visual Studio (the free Express edition will do, though the Professional edition is better)
  • Some experience with C# or Visual Basic -- or at least with an object-oriented framework such as Java or C++.

It helps to have a "how to" guide, and I've written one of those. And if you're the sort of person who learns best in the classroom, you can now take a class.

Are you wondering whether the class right for you? Watch this video (about 4 minutes long, in which I do my best Troy McClure impersonation). I'll explain what custom tasks are and what you need to know in order to build them. I'll also explain what you can expect to learn from the class, and the skills you should have before you enroll.


To enroll:
Visit the support.sas.com SAS Training site and find an offering that works with your schedule and location.

Post a Comment

How to split one data set into many

splitdataBack in the day when the prison system forced inmates to perform "hard labor", folks would say (of someone in prison): "He's busy making little ones out of big ones." This evokes the cliché image of inmates who are chained together, forced to swing a chisel to break large rocks into smaller rocks. (Yes, it seems like a pointless chore. Here's a Johnny Cash/Tony Orlando collaboration that sets it to music.)

SAS programmers are often asked to break large data sets into smaller ones. Conventional wisdom says that this is also a pointless chore, since you can usually achieve what you want (that is, process a certain subset of data) by applying a WHERE= option or FIRSTOBS=/OBS= combination. Splitting a data set creates more files, which occupy more disk space and forces more I/O operations. I/O and disk access is often the most expensive part of your SAS processing, performance-wise.

But if the boss asks for broken-up data sets, you might as well spend the least possible effort on the task. Let's suppose that you need to break up a single data set into many based on the value of one of the data columns. For example, if you need to break SASHELP.CARS into different tables based on the value of Origin, the SAS program would look like:

DATA out_Asia;
 set sashelp.cars(where=(origin='Asia'));
run;
DATA out_Europe;
 set sashelp.cars(where=(origin='Europe'));
run;
DATA out_USA;
 set sashelp.cars(where=(origin='USA'));
run;

I'm going to admit right now that this isn't the most efficient or elegant method, but it's something that most beginning SAS programmers could easily come up with.

Writing the above program is easy, especially since there are only 3 different values for Origin and I've memorized their values. But if there are more discrete values for the "split-by" column, the task could involve much more typing and has a high possibility for error. This is when I usually use PROC SQL to generate the code for me.

If you've read my article about implementing BY processing for an entire SAS program, you know that you can use PROC SQL and SELECT INTO to place data values from a data set into a macro variable. For example, consider this simple program:

proc sql;
 select distinct ORIGIN into :valList separated by ',' from SASHELP.CARS;
quit;

It creates a macro variable VALLIST that contains the comma-separated list: "Asia,Europe,USA".

But we can use SAS functions to embellish that output, and create additional code statements that weave the data values into SAS program logic. For example, we can use the CAT function to combine the values that we query from the data set with SAS keywords. The results are complete program statements, which can then be referenced/executed in a SAS macro program. I'll share my final program, and then I'll break it down a little bit for you. Here it is:

/* define which libname.member table, and by which column */
%let TABLE=sashelp.cars;
%let COLUMN=origin;
 
proc sql noprint;
/* build a mini program for each value */
/* create a table with valid chars from data value */
select distinct 
   cat("DATA out_",compress(&COLUMN.,,'kad'),
   "; set &TABLE.(where=(&COLUMN.='", &COLUMN.,
   "')); run;") into :allsteps separated by ';' 
  from &TABLE.;
quit;
 
/* macro that includes the program we just generated */
%macro runSteps;
 &allsteps.;
%mend;
 
/* and...run the macro when ready */
%runSteps;

Here are the highlights from the PROC SQL portion of the program:

  • SELECT DISTINCT ensures that the results include just one record for each unique value of the variable.
  • The CAT function concatenates a set of string values together. Note that CATX and CATS and CATT -- other variations of this function -- will trim out white space from the various string elements. In this case I want to keep any blank characters that occur in the data values because we're using those values in an equality check.
  • The program calculates a name for each output data set by using each data value as a suffix ("OUT_dataValue"). SAS data set names can contain only numbers and letters, so I use the COMPRESS function to purge any invalid characters from the data set name. The 'kad' options on COMPRESS tell it to keep only alpha and digit characters.
  • The resulting program statements all end up in the &ALLSTEPS macro variable. I could just reference the &ALLSTEPS variable in the body of the SAS program, and SAS would run it as-is. Instead I chose to wrap it in the macro %runSteps. This makes it a little bit easier to control the scope and placement of the executable SAS program statements.

"By each value of a variable" is just one criterion that you might use for splitting a data set. I've seen cases where people want to split the data based on other rules, such as:

  • Quantity of observations (split a 3-million-record table into 3 1-million-record tables)
  • Rank or percentiles (based on some measure, put the top 20% in its own data set)
  • Time span (break up a data set by year or month, assuming the data records contain a date or datetime variable)

With a small modification, my example program can be adapted to serve any of these purposes. What about you? Are you ever asked to split up SAS data sets, and if so, based on what criteria? Leave a comment and tell us about it.

Post a Comment

SAS employees are now easier to spot on Communities

Since the launch of Communities on SAS, hundreds of SAS employees have been among you. Some SAS employees made themselves known by selecting a telling user name (such as Cynthia@SAS), but others remained camouflaged or incognito, keeping their secret identities like the SAS superheroes they are.

That's about to change. This week, we are revealing all SAS staffers on the Communities by changing their status indicators to "SAS Employee", featuring the familiar SAS logo. We're making this change to help make Communities on SAS more valuable and relevant to you. We know that you enjoy interacting with SAS employees here; now you'll have a clearer view into when that's happening.

You'll see this take effect in several places. For example, for the communities that have a "Top Participants" roll, you might see some SAS folks appear in the list:

sasemp_statusroll
When you hover your mouse cursor over a user name, or drill down to see more details about a community member, you will also see the "SAS Employee" designation.

sasemp_user
With the introduction of the "SAS Employee" status, you will no longer see the familiar "rank" status for these users. So you won't be able to tell -- at a glance -- whether a SAS Employee has achieved Expert, Master, or merely Novice levels of contribution. We hope that you'll appreciate all SAS employees as experts in their respective areas, even if the ranking isn't spelled out for you.

We hope that you enjoy the change. If you have feedback or ideas, please let us know!

Post a Comment

Using SAS Enterprise Guide with your local SAS installation

serverlist_withlocalIf you have SAS Enterprise Guide and SAS for Windows installed on a machine together, they should Just Work. There is no special setup required. But...what if they don't?

I've posted an article in the SAS Enterprise Guide community about this topic. Read the article to learn:

  • How to select "No profile" mode in SAS Enterprise Guide.
  • How to add your Local SAS into the mix when you're connected to a SAS Metadata environment
  • How to "fix" your local system when SAS Enterprise Guide can't find your local SAS installation.

See the full article >> Using SAS Enterprise Guide with your local SAS installation

If you find the article to be helpful, please give it a rating. (You will need to sign in with your SAS profile to add a rating.) Positive ratings will make it easier for other users to find the information. And if you think the article needs something else to make it more useful, leave a comment on the article or here on the blog.

Side note about Communities on SAS

I've always been a big fan of the Communities on SAS, where thousands of SAS practitioners interact to learn from each other. A good number of SAS employees also participate in the discussions, which means that many of the answers about SAS technology are coming directly from the developers who created it. But it's your participation that makes the communities rich and engaging.

And now I have a more professional interest in the communities, as I've just moved into the role of managing our SAS Online Communities program. My team of community managers would love to hear from you about what you like and what you think could be improved. We have big plans for the communities program, and your input is essential to help us build the space where you want to spend your time. Post back in the comments here, or send us your feedback using this form (select Discussion Forums or Communities as the category).

Post a Comment

Why your DDE programs don't work anymore

Hello, 1992 called. They want their DDE Excel automation back.

DDE broken?Perhaps the title of this article is too pessimistic. Of course your SAS programs that use DDE (dynamic data exchange) can still work perfectly, as long as you situate your SAS software and its DDE "partner" (usually Microsoft Excel) to run on the same Windows PC. DDE is still documented and supported in SAS 9.4.

But for the growing number of users who modernize to a centralized SAS environment, the legacy of DDE is a big challenge to bring forward. Your new environment might include the benefits of SAS Grid Computing, SAS Visual Analytics, stored processes, and more manageable security. You might run your SAS programs using SAS Enterprise Guide or even a web browser. But with all of that shiny new tech and its distributed architecture, the simple local arrangement that allows DDE to function...well, it falls apart.

Let's look at how DDE works. This data exchange relies on two consenting Windows processes, both running on a single machine, to communicate with each other using special Windows messages. In SAS programs, this usually takes the form of SAS spawning Microsoft Excel, sending a command to reference a particular cell or range of cells in a sheet, and poking in some values that were computed in SAS. If your SAS session is now running on a remote machine (often a non-Windows machine), then SAS cannot use DDE to talk to your local Microsoft Excel application. As the man says, "what we've got here...is failure to communicate."

For those customers who have a lot invested in DDE (some have hundreds of programs!) and no time/budget to adjust processes away from it, I usually recommend a simple stop-gap approach: maintain a designated machine with SAS for Windows to do your DDE grunt work, even as you move other processes to an enterprise SAS environment.

But going forward, I encourage customers to look at the alternatives supported by new features in SAS that are more in line with today's topology (SAS on a remote server, SAS Enterprise Guide or other local client on the PC). These features can replace many (but not all) of the legacy DDE uses that are out there.

DDE is still supported in Microsoft Excel. We cannot say for how long, as Microsoft has put more emphasis on VBA, .NET, or PowerShell for Excel automation instead. But since DDE works only between two Windows processes (SAS and Excel in this case) on the same machine, it's an outmoded approach that's incompatible with many IT setups.

Some DDE alternatives

The SAS Add-In for Microsoft Office offers the most flexible method for complete control over the format and structure of your spreadsheet. It turns the problem on its head: instead of relying on a batch SAS program to push content into Excel, you simply use Excel to pull your SAS content into the spreadsheet, exactly where and how you want it. You can use SAS stored processes to encapsulate whatever SAS operation you need.

Within the SAS Add-In, you can also use specific cells and ranges as input into stored processes; it's just as flexible to inject your Excel content into SAS.

You can use Office scripting to automate the process (like a batch job), so the process can happen unattended. The consumers of your Excel documents do not need the SAS Add-In for Microsoft Office in order to view the results.

I know that not everyone is lucky enough to have the SAS Add-In. For batch SAS users, ODS tagsets.ExcelXP -- or its SAS 9.4 descendant ODS EXCEL -- can be used to place formatted report content into an Excel spreadsheet. Here's an example use for ODS EXCEL, which works as a "one-way" push from SAS into Excel.

Also, PROC EXPORT now supports adding sheets to existing files, or replacing entire sheets in place. That's flexibility that didn't exist before, when some users turned to DDE to fill the gap.

Aside from these SAS-centric approaches, creative programmer types can use script (VBS, PowerShell, and other) to plug their SAS data results into a spreadsheet as a post-process (which many customers spawn within their SAS programs).

Thinking of DDE as technical debt

Weaning yourself off of DDE is easier said than done, I'll admit. Twenty years ago DDE was a boon for SAS developers who needed to deliver Excel content to picky constituents. I played my part: I wrote the SAS Companion for Microsoft Windows (Release 6.11!) and crafted some of the examples that still exist in the documentation.

However, I now consider DDE programs to be a form of "technical debt" that organizations will have to pay off sooner or later.

If your "DDE bill" hasn't come due yet, you're fortunate. But if you're planning to write another SAS program that relies on DDE, consider the future generations. Today's kids are writing SAS programs in iPads and web browsers, and DDE is about as hip as a rotary-dial phone. (Yes, it still works, but it does make your fingers tired.)

Post a Comment

New SAS programming features in SAS Enterprise Guide 7.1

SAS Enterprise Guide 7.1 began shipping last week. Of the many new features, some are "biggies" while others are more subtle. My favorite new features are those for SAS programmers, including several items that I've heard customers ask for specifically. I'll describe them briefly here; the SAS Enterprise Guide online help contains more details.

Track program history

This is one of the biggies. If you have SAS programs in your SAS Enterprise Guide project, you can now track your changes in those programs using standard source control management methods.

eg71_commit
You can "commit", view history, revert changes, compare versions, and even see an annotated "blame" view that shows exactly when you introduced a change that broke your program.

eg71_blame
The program history feature relies on a "hyperlocal" Git repository within your EGP file, so you can't use this to track changes to SAS programs that you store outside of the project. But SAS Enterprise Guide 7.1 also supports integration with a file-system-based Git repository if you set one up using other tools. The SAS integrated menus/tools will still help you to see your program's heritage.

eg71_newscm
Why Git? Functionally, it fits the purpose. And the SAS team was able to embed the necessary pieces within the application, so you don't need to install additional tools before getting started. And besides, all of the cool kids use Git these days. If you need to work with Subversion or another tool, you can still use this file-system technique.

Smart highlighting in the program editor

Double-click on a word in the editor to highlight it, and instantly see all other occurrences of that word highlighted in your program view. That's what puts the "smart" in "smart highlighting".

It's amazingly useful for finding all occurrences of a variable name, data set name, or an embarrassing misspelling.

eg71_smarthighlight

Project log summary window

The Project Log shows you a complete aggregated view of your SAS logs within your project; it's been part of SAS Enterprise Guide for several years. The log content is comprehensive, but often difficult to navigate because it holds so much. Now the popular Log Summary view (introduced in release 6.1) has made it to the Project Log, simplifying your journey through the log content.

eg71_projlogsummary

Project-level Search

The search for a "search" feature led me to create the EGP Search tool, which has been very popular among SAS Enterprise Guide "power users". Now there is a built-in search feature that allows you to search the current project for text in any project element, including tasks, programs, and results.

eg71find

(The built-in search feature doesn't search multiple project files, so my EGP Search tool isn't obsolete just yet.)

SAS Macro Variable viewer and SAS System Options viewer

Many SAS programmers have downloaded these two custom tasks from this blog. The macro variable viewer shows all of the current SAS macro variables and their values, plus allows a quick method to evaluate macro expressions. The system options viewer shows all of the SAS options, with their values and meanings. Thanks to the popularity of the custom tasks, the R&D team agreed to include them in the main application. These tasks are now "first-class citizens" on the Tools menu.

eg71_newtools

But wait, there's more

I look forward to discussing more new features, including: integration with SAS Studio tasks, with SAS Visual Analytics and the LASR server, some new UI niceties for finding tasks and organizing Favorites, and much more. It's a big release with plenty of treasures to find -- and even I'm still discovering them!

Post a Comment

Don't panic: maybe your XLSX file is already opened

As you can tell from my recent posts (see here and here), I've been working with SAS and Microsoft Excel files quite a bit. I'm really enjoying the ability to import an XLSX file in my 64-bit SAS for Windows without any additional setup.

After one long afternoon of back-and-forth between Excel and SAS, I ran into this alarming error message:

ERROR: Error opening XLSX file -> C:\Projects\MyData.xlsx .  It is either not 
an Excel spreadsheet or it is damaged.   Error code=80001019
Requested Input File Is Invalid
ERROR: Import unsuccessful.  See SAS Log for details.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE IMPORT used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds

It's a scary message, and I panicked -- but just briefly. I soon remembered that Microsoft Excel likes to place an exclusive file lock on spreadsheet, so if you have it open in Excel, nothing else will be able to read it. My file wasn't "damaged" -- it was simply in use.

I could wish for a better error message like: "Excuse me sir, but it appears that file is already opened by another application. Would you mind closing it so that we can read the data? I mean, whenever it's convenient for you."

Once I closed Microsoft Excel and reran my SAS program, all was good. Whew!

Post a Comment