Tuesday, August 12, 2014

SAS: Number of hours between two DATETIME variables.

I tried several methods to get the number of hours between two DATETIME variables, but they were wrong.  Then I stumbled upon this:  http://support.sas.com/kb/24/585.html



/* Sample 1 - Calculate the difference between two SAS dates           */
/*                                                                     */
/* A SAS date value represents the number of days between January 1,   */
/* 1960 and the specific date.  To produce the difference in days      */
/* between two SAS date values, take the more recent date and subtract */
/* the other date.                                                     */

data dates; 

  /* Date constant syntax -- 'ddmmmyy'd */                             
  date1='19Jul2000'd;                      
  date2='19Jan2000'd;                      
  days=date1-date2;                        
  put "Difference in " days=;              
run;                                     
               
 
/* Sample 2 -- Calculating the difference between two SAS datetimes    */
/*                                                                     */
/* A SAS datetime value represents the number of seconds since         */
/* midnight of January 1, 1960 and the specified datetime.  To         */
/* produce the difference in seconds between two SAS datetime values,  */
/* take the greater of the two datetime values and subtract the other  */
/* datetime.  To convert the difference in seconds to represent the    */
/* difference in hours, divide the difference in seconds by 3600       */
/* (60 seconds x 60 minutes) and use the ROUND function to round the   */
/* value up to the nearest hour.  To convert the difference in seconds */
/* to represent the difference in days, divide the difference in       */
/* seconds by 86400 (60 seconds x 60 minutes x 24 hours) and use the   */
/* ROUND function to round the value up to the nearest day.            */                                                                        
                                                                        
data datetime;  

  /* Datetime constant syntax -- 'ddmmmyy:hh:mm:ss<.s>'dt */                                                        
  dtime1='01Jun2000:08:00:00'dt;       
  dtime2='31May2000:16:00:00'dt;       
  seconds=dtime1-dtime2;               
  hours=round((dtime1-dtime2)/3600);   
  days=round((dtime1-dtime2)/86400);   
  put "Difference in " seconds= ;      
  put "Difference in " hours= ;        
  put "Difference in " days= ;         
run;

No comments:

Post a Comment