Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active September 2, 2019 21:21
Show Gist options
  • Save nilforooshan/ab1c5c26164f4fb072a80e100864e79d to your computer and use it in GitHub Desktop.
Save nilforooshan/ab1c5c26164f4fb072a80e100864e79d to your computer and use it in GitHub Desktop.
R: Deduct times

R function to deduct times

The function:

DeductTimes = function(timeA, timeB) # "HH:MM:SS", timeA - timeB
{
   Atime = unlist(strsplit(timeA, "[:]"))
   Btime = unlist(strsplit(timeB, "[:]"))
   HHded = as.integer(Atime[1]) - as.integer(Btime[1])
   MMded = as.integer(Atime[2]) - as.integer(Btime[2])
   SSded = as.integer(Atime[3]) - as.integer(Btime[3])
   if(HHded<0) HHded = HHded + 24 # timeA belongs to the next date
   if(SSded!=0) {
      MMded = MMded + floor(abs(SSded)/60) * SSded / abs(SSded)
      SSded = (abs(SSded) %% 60) * SSded / abs(SSded) }
   if(MMded!=0) {
      HHded = HHded + floor(abs(MMded)/60) * MMded / abs(MMded)
      MMded = (abs(MMded) %% 60) * MMded / abs(MMded) }
   if(SSded < 0) {
      SSded = SSded + 60
      MMded = MMded - 1 }
   if(MMded < 0) {
      MMded = MMded + 60
      HHded = HHded - 1 }
   print(paste(HHded, MMded, SSded, sep=":"))
}

Example:

DeductTimes("01:33:17", "00:46:59")

Output:

[1] "0:46:18"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment