简体   繁体   中英

dealing with time in r difference between two times

I have two columns

starttime                      endtime
2019-11-05 18:02:04            2019-11-05 00:02:04
2019-08-02 20:18:00            2019-0802  01:10:00
2019-12-07 17:28:00            2019-12-07 18:00:00

I am trying to find the difference in time between starttime and endtime

mutate(col = difftime(endtime,starttime,units = "hours")

but i am getting negative hours which makes no sense, and i need it to be endtime - startime because it would mess up things for the dataframe that I have I beleive that 0.533 is right I got col -18 -19 0.533

We can increment the endtime by 1 day if startttime > endtime and then use difftime

library(dplyr)

df %>%
  mutate(endtime = if_else(starttime > endtime, endtime + 86400, endtime), 
         col = difftime(endtime,starttime,units = "hours"))

#            starttime             endtime             col
#1 2019-11-05 18:02:04 2019-11-06 00:02:04 6.0000000 hours
#2 2019-08-02 20:18:00 2019-08-03 01:10:00 4.8666667 hours
#3 2019-12-07 17:28:00 2019-12-07 18:00:00 0.5333333 hours

data

df <- structure(list(starttime = structure(c(1572976924, 1564777080, 
1575739680), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
endtime = structure(c(1572912124, 1564708200, 1575741600), class = c("POSIXct", 
"POSIXt"), tzone = "UTC")), row.names = c(NA, -3L), class = "data.frame")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM