Alessandro Jacopson
Alessandro Jacopson

Reputation: 18665

R: how to get the number of seconds from a string like "HH:MM:SS.CC"

I have a string like this one 00:05:33.91 that means 5 minutes 33 seconds and 91/100 of a second.

How can I get the total number of seconds? In the example it is 5*60+33+91/100 = 333.91 seconds.

Upvotes: 2

Views: 527

Answers (2)

Sacha Epskamp
Sacha Epskamp

Reputation: 47582

This works assuming you won't have a time of longer than 24 hours. With a vector foo containing characters as you have:

foo <- c("00:05:33.91","00:05:55","00:09:01.11")

We can obtain the total time as followed:

as.numeric(as.difftime(foo,format="%H:%M:%OS",units="secs"))

Upvotes: 7

voytech
voytech

Reputation: 380

You should divide the string into substrings containing numbers. You can use regexp to extract group for each time unit, or use a split(".") method of string. This will result with array of string, where the first would be "00:05:33" and the second "91" .

After that you can once again make a split(":"), which will result in array of string where first element is "00" , second "05" and third is "33". Then you should use String.parseInt for each number, and when you have numbers you can perform arithmetic on it.

I'm not sure, but maybe Yoda Time libraries will help You to achieve this faster and better. For example in Yoda you can parse the given string directly to date, and the getSeconds() - maybe this will work, but I'm not sure. I think that you should firstly try to figure it out by yourself as it is really simple task, and when you completely have no idea how to achieve this, then you should search for help.

Upvotes: 0

Related Questions