Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert mm:ss.00 to seconds.00?

Tags:

time

r

I've got some performance time data in mm:ss.00 format (i.e. 02:15.45, or 00:34.58). R is recognizing the variable as a factor, but I'd like to convert each performance time to just seconds (i.e. 02:15.45 to 135.45). I've searched for an answer but can't seem to find a way to make it work. Thanks in advance.

like image 298
Scott Maw Avatar asked May 31 '12 14:05

Scott Maw


3 Answers

Using lubridate package (part of tidyverse):

library(lubridate)
period_to_seconds(hms("12:12:54"))
like image 139
inhuretnakht Avatar answered Oct 22 '22 07:10

inhuretnakht


Here's one I've used for a number of years. It's vectorized, too.

toSeconds <- function(x){
   if (!is.character(x)) stop("x must be a character string of the form H:M:S")
   if (length(x)<=0)return(x)

   unlist(
      lapply(x,
         function(i){
            i <- as.numeric(strsplit(i,':',fixed=TRUE)[[1]])
            if (length(i) == 3) 
               i[1]*3600 + i[2]*60 + i[3]
            else if (length(i) == 2) 
               i[1]*60 + i[2]
            else if (length(i) == 1) 
               i[1]
         }  
      )  
   )  
} 

And the reverse (preserves fractional seconds to the number of digits requested:

secondsToString <- function(x,digits=2){
   unlist(
      lapply(x,
         function(i){
            # fractional seconds
            fs <- as.integer(round((i - round(i))*(10^digits)))
            fmt <- ''
            if (i >= 3600)
               fmt <- '%H:%M:%S'
            else if (i >= 60)
            fmt <- '%M:%S'
            else
               fmt <- '%OS'

            i <- format(as.POSIXct(strptime("0:0:0","%H:%M:%S")) + i, format=fmt)
            if (fs > 0)
               sub('[0]+$','',paste(i,fs,sep='.'))
            else
               i
         }
      )
   )
}
like image 19
Jeff Avatar answered Oct 22 '22 06:10

Jeff


Look into strptime. Specifically

t = "02:15.45"
(as.numeric(as.POSIXct(strptime(t, format = "%M:%OS"))) - 
    as.numeric(as.POSIXct(strptime("0", format = "%S"))))

This will work, but is possibly a little awkward (doing it this way mostly because of POSIXct's annoying automatic unit conversion...)

like image 10
Fhnuzoag Avatar answered Oct 22 '22 07:10

Fhnuzoag