【问题标题】:How can I subtract time between two time variables?如何减去两个时间变量之间的时间?
【发布时间】:2019-11-27 09:23:25
【问题描述】:

我有两列由“22:49”和“00:18”等字符值组成。它们代表小时和分钟的时间值。我怎样才能得到这两列之间的区别?我希望我的结果是两个值之间的分钟数。

【问题讨论】:

  • 某处是否有日期,或者所有差异都应该是模数 1440?
  • 没有日期。只是时间。

标签: r


【解决方案1】:

如果您的数据在一列中,那么

dat <- data.frame(x = c("22:49", "00:18"), stringsAsFactors = FALSE)
dat$x <- as.POSIXct(sprintf("2000-01-01 %s:00", dat$x))
diffs <- diff(dat$x)
units(diffs) <- "mins"
diffs <- as.numeric(diffs) %% 1440
diffs
# [1] 89

使用n 行数据,这将为您提供n-1 差异......所以此时您可能想要c(0, diffs)


如果您的数据位于两个不同的列中:

dat <- data.frame(x1 = "22:49", x2 = "00:18", stringsAsFactors = FALSE)

as.numeric(do.call(difftime, c(unname(
  lapply(dat[,c("x2", "x1")],
         function(d) as.POSIXct(sprintf("2000-01-01 %s:00", d)))), units = "mins"))) %% 1440
# [1] 89

注意本例中x2 然后x1 的顺序。

【讨论】:

  • lubridatewith(dat, diff(period_to_seconds(hm(x))/60) %% 1440)
【解决方案2】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
相关资源
最近更新 更多