Contributor
Posts: 59

# How to calculate datetime difference between two date values in minutes and hours

Hi all,

I need help (SAS code) in calculating difference in minutes and hours for datetime variables. I have attached a copy of my data.

Here I have several Reg_Nos and the corresponding culture_dates (datetime). Some of the Reg_nos have multiple culture_date which are in different row compared to the first culture_date for that Reg_no (eg. I have highlighted in red).

I need to find the difference in minutes and hours from the first culture_date to the next cultre_date if a Reg_No has more than one culture_date.

Thanks for the help!

Satish

Posts: 3,057

## Re: How to calculate datetime difference between two date values in minutes and hours

1. Sort by Reg_no and Culture Date
2. In the sorted data set, compute the difference between the current culture date and the previous culture date (use the LAG function)
3. Compute the number of minutes and hours from the result in step 2.

Note: you'd want to not count the cases where the current reg_no and the previous reg_no don't match, again LAG can help you determine this.

--
Paige Miller
Frequent Contributor
Posts: 96

## Re: How to calculate datetime difference between two date values in minutes and hours

Here's a sample code using retain instead of lag.

data reg_no(drop=day row);
do reg_no=1 to 10;
do row = 1 to reg_no;
day=mdy(12,31,2014);
culture_date= DHMS(day+row,reg_no+row*row,reg_no,0) ;
format culture_date datetime.;
format day ddmmyy.;
output;
end;
end;
run;

data reg_no2(drop=lastdate);
set reg_no;
retain lastdate firstdate;
format delay time. ;
format delay_since_first time. ;
by reg_no;
if first.reg_no then
do;
lastdate=culture_date;
firstdate=culture_date;
end;
else do;
delay= culture_date - lastdate;
lastdate= culture_date;
delay_since_first= culture_date - firstdate;
end;
run;

Discussion stats
• 2 replies
• 370 views
• 0 likes
• 3 in conversation