Home > Back-end >  How to change Time format in R?
How to change Time format in R?

Time:06-06

I have added a new column RIDE_LENGTH using mutate function as follows.

df2 <- mutate(df2, RIDE_LENGTH = (ENDED_AT - STARTED_AT) ENDED AT & STARTED AT is in HH:MM:SS format, but my new column is showing the result in seconds only example : 12:05:00 - 12:03:00 = 120 secs. I need the answer to be in the same format as 00:02:00. If anyone can tell me how to do that would be a great help.

CodePudding user response:

You can use

library(lubridate)
RIDE_LENGTH <- seconds_to_period(RIDE_LENGTH)

CodePudding user response:

There are a few ways in the lubridate package, depending on your desired output. Take your pick:

library(dplyr)

df  <- data.frame(
  STARTED_AT = as.POSIXct("2022-06-06 12:03:00 UTC"),
  ENDED_AT = as.POSIXct("2022-06-06 12:05:00 UTC")
)

df  |>
  mutate(
    RIDE_LENGTH_base = ENDED_AT - STARTED_AT,
    RIDE_LENGTH_lubridate_difftime = lubridate::as.difftime(ENDED_AT - STARTED_AT), 
    RIDE_LENGTH_period = lubridate::as.period(ENDED_AT - STARTED_AT), 
    RIDE_LENGTH_duration = lubridate::as.duration(ENDED_AT - STARTED_AT)    
    )
#            STARTED_AT            ENDED_AT RIDE_LENGTH_base RIDE_LENGTH_lubridate_difftime RIDE_LENGTH_period RIDE_LENGTH_interval
# 1 2022-06-06 12:03:00 2022-06-06 12:05:00           2 mins                         2 mins              2M 0S    120s (~2 minutes)
  • Related