BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
njgrubic
Fluorite | Level 6

In my code I am attempting to calculate the elapsed time between two time points (response time). I have formatted all of my time variables into the "time." format in SAS. In majority of cases, I am able to calculate a positive elapsed time by subtracting time point 2 from time point 1 (i.e. 19:24:01 - 19:19:22 = 0:04:39 = 4 minutes 39 seconds elapsed).

 

Although there is a select group of observations where the time window crossed 12am (i.e.<23:59:59  and >00:00:00). Using my method to calculate the elapsed time, I am getting negative elapsed time. For example the time interval between 11:58:35PM and 0:05:51AM is calculated as -23:52, when the true interval should be 0:07:16 (7 minutes 16 seconds).

 

Does anyone know of a simple way to correct these observations? See current simple SAS code below:

data datawithtime;
set rawdata;
elapsedtime=time2-time1;
run;
1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20

If so, just add the number of seconds in a day (86400) to the result if it is negative.

 

data have;
input (time1 time2)(:hhmmss8.);
format time: timeampm.;
datalines;
23:58:35 00:05:51AM
;

data want;
   set have;
   elapsedtime = ifn(time2 < time1, time2 - time1 + 86400, time2 - time1);
   format elapsedtime time.;
run;

 

Result:

 

time1        time2        elapsedtime 
11:58:35 PM  12:05:51 AM  0:07:16 

View solution in original post

3 REPLIES 3
Reeza
Super User
Do you have the dates somewhere? If you can add the date component in, that's the best fix. Otherwise, could you also have times that are well over 24 hours which may also cross dates and you wouldn't know?

For negatives you could just add dates but I wouldn't trust that to catch all cases, so it depends on your situation.
PeterClemmensen
Tourmaline | Level 20

It is safe to assume that the time point in time2 is later than the point in time1, right?

PeterClemmensen
Tourmaline | Level 20

If so, just add the number of seconds in a day (86400) to the result if it is negative.

 

data have;
input (time1 time2)(:hhmmss8.);
format time: timeampm.;
datalines;
23:58:35 00:05:51AM
;

data want;
   set have;
   elapsedtime = ifn(time2 < time1, time2 - time1 + 86400, time2 - time1);
   format elapsedtime time.;
run;

 

Result:

 

time1        time2        elapsedtime 
11:58:35 PM  12:05:51 AM  0:07:16 

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 3 replies
  • 990 views
  • 2 likes
  • 3 in conversation