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

Viewed 125748

In the following data frame the 'time' column is character in the format hour:minute:second

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)

How can I convert 'time' column to a dedicated time class, so that I can perform arithmetic calculations on it?

6 Answers

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

Using the ITime class in data.table package:

ITime is a time-of-day class stored as the integer number of seconds in the day.

library(data.table)
(it <- as.ITime(time))
# [1] "00:00:01" "01:02:00" "09:30:01" "14:15:25"

it + 10
# [1] "00:00:11" "01:02:10" "09:30:11" "14:15:35"


diff(it)
# [1] "01:01:59" "08:28:01" "04:45:24"

lubridate allows good flexibility on the time format :

library(lubridate)

time_hms_1<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
hms(time_hms_1)
#> [1] "1S"          "1H 2M 0S"    "9H 30M 1S"   "14H 15M 25S"


time_hms_2<-c("0:00:01", "1:02:00", "9:30:01", "14:15:25")
hms(time_hms_2)
#> [1] "1S"          "1H 2M 0S"    "9H 30M 1S"   "14H 15M 25S"

time_hm_1<-c("00:00", "01:02", "09:30", "14:15")
hm(time_hm_1)
#> [1] "0S"         "1H 2M 0S"   "9H 30M 0S"  "14H 15M 0S"

time_hm_2<-c("0:00", "1:02", "9:30", "14:15")
hm(time_hm_2)
#> [1] "0S"         "1H 2M 0S"   "9H 30M 0S"  "14H 15M 0S"

Created on 2020-07-03 by the reprex package (v0.3.0)

Yet another alternative using the hms package.

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)

Convert column time to class hms

# install.packages("hms")
library(hms)
df$time <- as.hms(df$time)

Perform arithmetic calculations

diff(df$time)
#01:01:59
#08:28:01
#04:45:24
Related