如何找到R中两个时间戳之间的差异?

时间:2019-07-10 19:05:01

标签: r posixct

我在数据框中有两个属于“时间”类的字段。分别命名为Time1Time2。我试图找出两者之间的时差。

CombinedFrame2$Duration <- difftime(CombinedFrame2$Time1, CombinedFrame2$Time2)

Error in as.POSIXct.numeric(CombinedFrame2$Time1) : 
  'origin' must be supplied

我如何让班级合作进行计算?

示例:


Time1       Time2       Duration
5:30:00     6:24:00     0:54:00

$ Time1  : POSIXlt, format: "2019-07-10 16:07:00" "2019-07-10 22:05:00" "2019-07-10 22:20:00" "2019-07-10 22:43:00" ...
 $ Time2   : POSIXlt, format: "2019-07-10 22:05:00" "2019-07-10 22:20:00" "2019-07-10 22:43:00" "2019-07-10 23:15:00" ...

> dput(head(CombinedFrame2[,c("Time1", "Time2")]))

structure(list(Time1 = structure(list(sec = c(0, 0, 0, 0, 
0, 0), min = c(7L, 5L, 20L, 43L, 15L, 35L), hour = c(16L, 22L, 
22L, 22L, 23L, 23L), mday = c(11L, 11L, 11L, 11L, 11L, 11L), 
    mon = c(6L, 6L, 6L, 6L, 6L, 6L), year = c(119L, 119L, 119L, 
    119L, 119L, 119L), wday = c(4L, 4L, 4L, 4L, 4L, 4L), yday = c(191L, 
    191L, 191L, 191L, 191L, 191L), isdst = c(1L, 1L, 1L, 1L, 
    1L, 1L), zone = c("EDT", "EDT", "EDT", "EDT", "EDT", "EDT"
    ), gmtoff = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_, 
    NA_integer_, NA_integer_)), class = c("POSIXlt", "POSIXt"
)), Time2 = structure(list(sec = c(0, 0, 0, 0, 0, 0), min = c(5L, 
20L, 43L, 15L, 35L, 55L), hour = c(22L, 22L, 22L, 23L, 23L, 23L
), mday = c(11L, 11L, 11L, 11L, 11L, 11L), mon = c(6L, 6L, 6L, 
6L, 6L, 6L), year = c(119L, 119L, 119L, 119L, 119L, 119L), wday = c(4L, 
4L, 4L, 4L, 4L, 4L), yday = c(191L, 191L, 191L, 191L, 191L, 191L
), isdst = c(1L, 1L, 1L, 1L, 1L, 1L), zone = c("EDT", "EDT", 
"EDT", "EDT", "EDT", "EDT"), gmtoff = c(NA_integer_, NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_)), class = c("POSIXlt", 
"POSIXt"))), row.names = c("1:1", "1:2", "1:3", "1:4", "1:5", 
"1:6"), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

您需要确保时间格式正确。请参见下面的代码。

您可以使用strptime()将时间格式化为小时,分钟和秒。

time1 <- "5:30:00"
time2 <- "6:24:00"
time1a <- strptime(time1,format="%H:%M:%S")
time2a <- strptime(time2,format="%H:%M:%S")
duration <- difftime(time2a,time1a)