Lubridate修复时间单位

时间:2017-06-21 07:42:20

标签: r lubridate

当我们采用两次相差时,单位会自动进行。

> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs
> ymd_hms("2016-05-09 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 59.98333 mins
> ymd_hms("2016-05-10 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 1.041655 days

如何在不使用difftime功能的情况下修复单位。

所以我可以做到以下几点:

VECTOR = c(ymd_hms("2016-05-10 16:17:03"),
           ymd_hms("2016-05-10 17:19:33"),
           ymd_hms("2016-05-10 19:55:03")
         )

diffs = diff(VECTOR)

IntervalsInHours = toHours(diffs)

此外,有没有办法知道在rubridate时间对象中使用的单位。例如,

> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs

此处使用的单位为seconds

4 个答案:

答案 0 :(得分:1)

请在下面尝试将时差转换为小时。

library(lubridate)
x=ymd_hms("2016-05-09 16:17:03") 
y=ymd_hms("2016-05-19 15:17:04")
diffs=as.duration(x-y)
IntervalsInHours=as.numeric(abs(diffs))/3600;IntervalsInHours

答案 1 :(得分:1)

或者您可以这样使用:

library(lubridate)
x=ymd_hms("2016-05-09 16:17:03") 
y=ymd_hms("2016-05-19 16:17:04")
diffs=as.duration(x-y);
IntervalsInHours=abs(diffs)/dhours(1);IntervalsInHours

答案 2 :(得分:1)

“你想使用diff函数来获取VECTOR元素之间的时间差,只能以指定的单位”

请尝试以下代码:(通过int_diff函数)

> VECTOR = c(ymd_hms("2016-05-10 16:17:03"),
+            ymd_hms("2016-05-10 16:17:04"),
+            ymd_hms("2016-05-10 17:19:33"),
+            ymd_hms("2016-05-10 19:55:03")
+ )
> as.numeric(int_diff(VECTOR))
[1]    1 3749 9330
> round(as.numeric(int_diff(VECTOR))/3600,2)
[1] 0.00 1.04 2.59

请注意,无论时间间隔min unit是否为秒,它总是按秒缩放。

> VECTOR = c(ymd_hms("2016-05-10 16:17:03"),
+            #ymd_hms("2016-05-10 16:17:04"),
+            ymd_hms("2016-05-10 17:19:33"),
+            ymd_hms("2016-05-10 19:55:03")
+ )
> as.numeric(int_diff(VECTOR))
[1] 3750 9330
> round(as.numeric(int_diff(VECTOR))/3600,2)
[1] 1.04 2.59

答案 3 :(得分:0)

我写了两个函数,以防有人觉得有用。

timeDiffUnitConvert = function(Diffs, to="day", roundingN = 1){      
  if(to == "day"){
    R = round(as.numeric(as.duration(Diffs))/3600/24,roundingN)
  } else if (to == "hour") {
    R = round(as.numeric(as.duration(Diffs))/3600, roundingN)
  } else if (to == "min") {
    R = round(as.numeric(as.duration(Diffs))/60, roundingN)
  } else if (to == "sec"){
    R = round(as.numeric(as.duration(Diffs)), roundingN)
  } else {
    stop("to which unit? it must be `day`, `hour`, `min` or `sec`.")
  }
  R
}

timeDiffVector = function(TimeVector, to="day", roundingN = 1, attachNaMode = "none"){
  R = timeDiffUnitConvert(diff(TimeVector), to = to, roundingN = roundingN)
  if(attachNaMode == "leading"){
    R = c(NA,R)
  } else if(attachNaMode == "trailing"){
    R = c(R,NA)
  } else{
    stop("check your attachNaMode: shall be either `leading` or `trailing`")
  }
  R
}