Home > OS >  How to calculate time difference in R using an dataframe
How to calculate time difference in R using an dataframe

Time:10-09

Have an large data frame where there's 2 columns (POSIXct) and need to calculate length of ride.

Dates are formatted as follows:

format: "2020-10-31 19:39:43"

Can use the difftime function, correct?

Thanks

CodePudding user response:

Given your data is using the correct POSIXct format you can simply subtract two dates to get the difference. No need for additional functions.

date1 <- as.POSIXct(strptime("2020-10-31 19:39:43", format = "%Y-%m-%d %H:%M:%OS"))
date2 <- as.POSIXct(strptime("2020-10-31 19:20:43", format = "%Y-%m-%d %H:%M:%OS"))

date1 - date2

Output: Time difference of 19 mins

CodePudding user response:

It depends what output format you want.
For example if you want month difference between two dates, you can use the "interval" function from library "lubridate"

library(lubridate)
interval(as.Date(df$date1),as.Date(df$date2) %/% months(1))

It also works with years, weeks, days, hours

  • Related