简体   繁体   中英

Time difference between two time stamps

I have a dataframe that contains the following datetime stamps of the class "POSIXct" "POSIXt" :

1899-12-30 08:00:37
1899-12-30 08:03:54
1899-12-30 08:05:31
1899-12-30 08:12:55

I need to calculate the difference (in minutes) between subsequent rows. The result for the first row should be (ie 08:03:54-08:00:37):

1899-12-30 08:00:37      3.28

I use this code to calculate the difference, but the outputs do not coincide with manual calculations.

c_time <- df$datetime
intervals = c(difftime(ymd_hms(c_time[2:length(c_time)]),
                                ymd_hms(c_time[1:(length(c_time)-1)]),
                                units="mins"),0)

You could use lubridate and dplyr . It is one option among others.

df <- data.frame(dtime = c(
"1899-12-30 08:00:37",
"1899-12-30 08:03:54",
"1899-12-30 08:05:31",
"1899-12-30 08:12:55"))

library(dplyr)
library(lubridate)
df %>%
  mutate(dtime = ymd_hms(dtime), 
         diff = lead(dtime) - dtime)
#>                 dtime          diff
#> 1 1899-12-30 08:00:37 3.283333 mins
#> 2 1899-12-30 08:03:54 1.616667 mins
#> 3 1899-12-30 08:05:31 7.400000 mins
#> 4 1899-12-30 08:12:55       NA mins

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