Reputation: 1238
data.frame(gid = c(1,1,1,2), gtime = c("2015-10-22 13:23:02", "2015-10-22 13:23:02", "2015-10-22 13:23:02", "2016-11-23 13:23:02"), wid = c (3,4,5,2) wtime = c("2015-10-22 13:33:02", "2015-10-22 13:53:02", "2015-10-22 14:23:02", "2016-11-23 13:28:02"), type = c("google", "google", "amazon", "yahoo")
How is it possible to take the difference between timestamp pf gtime and wtime? Example of expected output:
data.frame(difference = c("10 minutes", "30 minutes", "60 minutes", "24 hours and 5 minutes"), gid = c(1,1,1,2), gtime = c("2015-10-22 13:23:02", "2015-10-22 13:23:02", "2015-10-22 13:23:02", "2016-11-23 13:23:02"), wid = c (3,4,5,2) wtime = c("2015-10-22 13:33:02", "2015-10-22 13:53:02", "2015-10-22 14:23:02", "2016-11-24 13:28:02"), type = c("google", "google", "amazon", "yahoo")
Upvotes: 0
Views: 50
Reputation: 388807
You can directly subtract the time after converting it to as.POSIXct
with(df, as.POSIXct(wtime) - as.POSIXct(gtime))
#Time differences in mins
#[1] 10 30 60 5
Also can use lubridate's ymd_hms
instead of as.POSIXct
.
library(lubridate)
with(df, ymd_hms(wtime) - ymd_hms(gtime))
Upvotes: 1
Reputation: 886938
We can convert to Datetime class and use difftime
with unit
specified as min
df1$difference <- with(df1, difftime(as.POSIXct(wtime),
as.POSIXct(gtime), unit = 'min'))
Wrap with as.numeric
if we need to remove the attribute
Upvotes: 1