Hours:Minutes:Seconds to Seconds

2.1k Views Asked by At

I am attempting to convert a long list of values in a column from Hours:Minutes:Seconds into just Seconds. The code I have below works fine as long as the values are in H:M:S format, but I have values in random rows that are just in the M:S format (so no hours). When I try to perform the below code on them, I obviously obtain an NA for each of those values. Is there a way that I can search for only the values in M:S format, and only the H:M:S format, and convert them separately? Do I need to add an hours value in each of the M:S values so I can convert all at once? My code below:

as.numeric(strptime(df$x, format="%H:%M:%S") - as.POSIXct(format(Sys.Date())), units="secs")

Example of data:
    Time
    12:22:05
    42:44

Example of data after running above:
    Time
    44525
    NA
2

There are 2 best solutions below

3
On

Try parse_date_time while using the lubridate package.

df$time <- parse_date_time(x = df$time, c("HMS","MS"))
0
On

Your proposal to add hours value to the M:S format seems also quite easy to implement :

x = c("12:22:05", "42:44")
x[nchar(x)<8] <- paste0("00:", x[nchar(x)<8])
as.numeric(strptime(x, format="%H:%M:%S") - as.POSIXct(format(Sys.Date())), units="secs")
## 44525  2564