Convert H:M:S character into number

Viewed 506

In a text file, I have a field with character values that look like this:

"00:01:53.910"

Where the value is in fact a time in hours:minutes:seconds.

I want to convert this to a numeric value. In this example, it should be 113.91 seconds.

Tried using this code in R and I get 1606287714

as.numeric(strptime("00:01:53.910",format='%H:%M:%OS'))

I believe the problem has to do with it adding the current date to the calculation because when I run

strptime("00:01:53.910",format='%H:%M:%OS')

I get "2020-11-25 00:01:53.91 MST"

4 Answers

Using libridate package

y <- hms("00:01:53.910")                                                      
y
# [1] "1M 53.91S"

seconds(y)                                                                    
#[1] "113.91S"

as.numeric(seconds(y))                                                     
# [1] 113.91

Here's a function that can do it:

library(tidyverse)

time_to_seconds <- function(time) {
  
  parts <- time %>% 
    strsplit(":|\\.") %>% 
    .[[1]] %>% 
    as.numeric
  
  seconds <- parts[1] * 60 * 60 + parts[2] * 60 + parts[3]
  
  seconds
}

time_to_seconds("00:01:53.910")
[1] 113

We can use period_to_seconds

library(lubridate)
period_to_seconds(hms(time))
#[1] 113.91

data

time <- "00:01:53.910" 

One base R option using as.POSIXct/strptime

t1 <- as.POSIXct('00:01:53.910', format='%H:%M:%OS', tz = 'UTC')
#t1 <- strptime('00:01:53.910', format='%H:%M:%OS', tz = 'UTC')
as.numeric(difftime(t1, Sys.Date(), units = 'secs'))
#[1] 113.91
Related