Convert hour:minute:second (HH:MM:SS) string to proper time class

Use the function chron in package chron:

time<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")

library(chron)
x <- chron(times=time)

x
[1] 00:00:01 01:02:00 09:30:01 14:15:25

Do some useful things, like calculating the difference between successive elements:

diff(x)
[1] 01:01:59 08:28:01 04:45:24

chron objects store the values internally as a fraction of seconds per day. Thus 1 second is equivalent to 1/(60*60*24), or 1/86400, i.e. 1.157407e-05.

So, to add times, one simple option is this:

x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26

Using base R you could convert it to an object of class POSIXct, but this does add a date to the time:

id<-c(1,2,3,4)
time<-c("00:00:01","01:02:00","09:30:01","14:15:25")
df<-data.frame(id,time,stringsAsFactors=FALSE)

as.POSIXct(df$time,format="%H:%M:%S")
[1] "2012-08-20 00:00:01 CEST" "2012-08-20 01:02:00 CEST"
[3] "2012-08-20 09:30:01 CEST" "2012-08-20 14:15:25 CEST"

But that does allow you to perform arithmetic calculations on them.


Another possible alternative could be:

time <- c("00:00:01","01:02:00","09:30:01","14:15:25")
converted.time <- as.difftime(time, units = "mins") #"difftime" class
secss <- as.numeric(converted.time, units = "secs")
hourss <- as.numeric(converted.time, units = "hours")
dayss <- as.numeric(converted.time, units="days")

Or even:

w <- strptime(x = time, format = "%H:%M:%S") #"POSIXlt" "POSIXt" class

Tags:

Time

R