[英]Time difference between two values
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")
如何区分时间戳 pf gtime 和 wtime 之间的差异? 预期 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")
我们可以转换为日期时间difftime
并使用unit
指定为min
的 difftime
df1$difference <- with(df1, difftime(as.POSIXct(wtime),
as.POSIXct(gtime), unit = 'min'))
如果我们需要删除属性,请用as.numeric
包装
转换成as.POSIXct
后可以直接减去时间
with(df, as.POSIXct(wtime) - as.POSIXct(gtime))
#Time differences in mins
#[1] 10 30 60 5
也可以使用 lubridate 的ymd_hms
代替as.POSIXct
。
library(lubridate)
with(df, ymd_hms(wtime) - ymd_hms(gtime))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.