1

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.

  • 3
    Convert them to a date-time class like `POSIXct` and then subtraction will work just fine. See [a couple options here](https://stackoverflow.com/q/12034424/903061). – Gregor Thomas Dec 09 '20 at 16:09

3 Answers3

1

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"))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

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

data

df <- data.frame(t1 = c("12:24:13", "10:04:39"), t2 = c("10:46:34", "09:43:23"))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

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.

Karthik S
  • 11,348
  • 2
  • 11
  • 25