Mori
Mori

Reputation: 135

Converting time in hh:mm:ss format to second or minutes

I have a column of time in this format: 43:46:18 which shows hh:mm:ss (h: hour, m: minutes, s: second), I want to convert this column to seconds (or minutes), but ":" is redundant and I do not know how I should deal with that?

Upvotes: 0

Views: 1508

Answers (2)

Miff
Miff

Reputation: 7951

The lubridate package contains some useful functions for dealing with dates and times, in particular hms is useful for reading times in your format. You could use this as in:

library(lubridate)

as.numeric(hms("43:46:18"))
# [1] 157578  #Conversion to seconds 

Upvotes: 2

G. Grothendieck
G. Grothendieck

Reputation: 270358

1) Define a function which separates the 3 parts of the times into a data frame of 3 columns, converts it to a matrix and then matrix multiplies that with a vector whose 3 components are the number of seconds in an hour, minute and second. Finally use c(...) to convert that from an nx1 matrix to a plain vector.

To test, apply that to the time column of the test data dat defined in the Note at the end. No packages are used.

time2sec <- function(x) {
  c(as.matrix(read.table(text = x, sep = ":")) %*% c(3600, 60, 1))
}

# test using dat from Note at the end
transform(dat, seconds = time2sec(time))

giving:

  id     time seconds
1  1 43:46:18  157578
2  2 43:46:18  157578

2) An alternate method is to convert to POSIXlt regarding the hour as a year and then convert that to seconds. This gives the same result as above. Again, no packages are used.

time2sec_2 <- function(x) {
  with(as.POSIXlt(x, format = "%Y:%M:%S"), 3600 * (year + 1900) + 60 * min + sec)
}

transform(dat, seconds = time2sec_2(time))

Note

dat <- data.frame(id = 1:2, time = "43:46:18")

Upvotes: 4

Related Questions