Reputation: 13
I have two columns 1) Start.Time 2) End.Time .
The data in both column is in chr format and " 00:00:00 ".
How could I get a column that has the duration? (End.Time. - Start.Time)
Thanks for any help.
Upvotes: 1
Views: 880
Reputation: 887951
We can also convert to ITime
with data.table
and get the difference
library(data.table)
setDT(df)[, duration := as.ITime(t1) - as.ITime(t2)]
-output
df
# t1 t2 duration
#1: 12:24:13 10:46:34 01:37:39
#2: 10:04:39 09:43:23 00:21:16
df <- data.frame(t1 = c("12:24:13", "10:04:39"), t2 = c("10:46:34", "09:43:23"))
Upvotes: 0
Reputation: 102880
You can try chron
package
transform(
df,
duration = chron(times = t1) - chron(times = t2)
)
such that
t1 t2 duration
1 12:24:13 10:46:34 01:37:39
2 10:04:39 09:43:23 00:21:16
Data
df <- data.frame(t1 = c("12:24:13", "10:04:39"), t2 = c("10:46:34", "09:43:23"))
Upvotes: 0
Reputation: 11548
You can try:
t1 <- c('12:24:13','10:04:39')
t2 <- c('10:46:34','09:43:23')
unclass(as.POSIXct(t1,format="%H:%M:%S")) - unclass(as.POSIXct(t2,format="%H:%M:%S"))
[1] 5859 1276
attr(,"tzone")
POSIXct is number of seconds since epoch, which is 1970-01-01. In above example, the output is difference between times in seconds.
Upvotes: 0