Tim Batten
Tim Batten

Reputation: 55

How to find the difference between two timestamps in R?

I have two fields in a dataframe that are of the class "times". Call it Time1 and Time2. I am trying to find the time difference between the two.

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

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

How do I get the classes to cooperate to do the calculation?

Example:


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")

Upvotes: 1

Views: 1824

Answers (1)

M Waz
M Waz

Reputation: 775

You need to make sure that your time is formatted correctly. See the code below.

You can use strptime() to format your time into hours, minutes, and seconds.

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)

Upvotes: 2

Related Questions