Handling time data

References

Relative time in seconds from a given time point

## Original time data
rawTime <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
## Convert to time. It becomes today's time, but that is ok if comparison is relative within a day.
(rawTime <- strptime(rawTime, format = "%H:%M:%S"))
## [1] "2014-05-05 23:03:20 EDT" "2014-05-05 22:29:56 EDT" "2014-05-05 01:03:30 EDT" "2014-05-05 18:21:03 EDT"
## [5] "2014-05-05 16:56:26 EDT"
## Conver to the unix time (time in seconds since 1970-01-01 00:00:00)
(unixTime <- as.numeric(rawTime))
## [1] 1399345400 1399343396 1399266210 1399328463 1399323386

## Time point that should be treated as time 0
zeroTime <- c("17:15:13")
(zeroTime <- strptime(zeroTime, format = "%H:%M:%S"))
## [1] "2014-05-05 17:15:13 EDT"
(zeroInUnixTime <- as.numeric(zeroTime))
## [1] 1399324513

## Using unix times (time in secons)
unixTime - zeroInUnixTime
## [1]  20887  18883 -58303   3950  -1127
## Using subration and as.numeric (this delegates its work to difftime)
as.numeric(rawTime - zeroTime, units = "secs")
## [1]  20887  18883 -58303   3950  -1127
## Using difftime directly
difftime(rawTime, zeroTime, units = "secs")
## Time differences in secs
## [1]  20887  18883 -58303   3950  -1127

Fully manual method

## Time as matrix
timesInString <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
timeMat <- do.call(rbind, lapply(strsplit(timesInString, ":"), as.numeric))
timeMat
##      [,1] [,2] [,3]
## [1,]   23    3   20
## [2,]   22   29   56
## [3,]    1    3   30
## [4,]   18   21    3
## [5,]   16   56   26
## Convert to seconds
(timeMat <- sweep(timeMat, MARGIN = 2, STATS = c(60*60, 60, 1), FUN = "*"))
##       [,1] [,2] [,3]
## [1,] 82800  180   20
## [2,] 79200 1740   56
## [3,]  3600  180   30
## [4,] 64800 1260    3
## [5,] 57600 3360   26
## Sum up
(timeInSeconds <- rowSums(timeMat))
## [1] 83000 80996  3810 66063 60986

## Zero time as vector
zeroTimeInString <- c("17:15:13")
zeroTimeVec <- as.numeric(strsplit(zeroTimeInString, ":")[[1]])
zeroTimeVec
## [1] 17 15 13
## Convert to secons
(zeroTimeVec <- zeroTimeVec * c(60*60, 60, 1))
## [1] 61200   900    13
## Sum up
(zeroTimeInSeconds <- sum(zeroTimeVec))
## [1] 62113

## Subtract
timeInSeconds - zeroTimeInSeconds
## [1]  20887  18883 -58303   3950  -1127