mackartist
mackartist

Reputation: 1

Added the sum of two POSIXct variable to get the the duration in hr : min : sec in a new variable in R

I would like to get the duration of two variables. I would like the result to in hr : min : sec format. Here is my code.

Total_Trips$Trip_Duration <- as.POSIXct(Total_Trips$started_at - Total_Trips$ended_at, format = "%H:%M:%S")

Here is the df info and the error.

'data.frame':   4558885 obs. of  13 variables:
 $ ride_id           : chr  "A847FADBBC638E45" "5405B80E996FF60D" "5DD24A79A4E006F4" "2A59BBDF5CDBA725" ...
 $ rideable_type     : chr  "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
 $ started_at        : POSIXct, format: "2020-04-26 17:45:14" "2020-04-17 17:08:54" "2020-04-01 17:54:13" "2020-04-07 12:50:19" ...
 $ ended_at          : POSIXct, format: "2020-04-26 18:12:03" "2020-04-17 17:17:03" "2020-04-01 18:08:36" "2020-04-07 13:02:31" ...
 $ start_station_name: chr  "Eckhart Park" "Drake Ave & Fullerton Ave" "McClurg Ct & Erie St" "California Ave & Division St" ...
 $ start_station_id  : chr  "86" "503" "142" "216" ...
 $ end_station_name  : chr  "Lincoln Ave & Diversey Pkwy" "Kosciuszko Park" "Indiana Ave & Roosevelt Rd" "Wood St & Augusta Blvd" ...
 $ end_station_id    : chr  "152" "499" "255" "657" ...
 $ start_lat         : num  41.9 41.9 41.9 41.9 41.9 ...
 $ start_lng         : num  -87.7 -87.7 -87.6 -87.7 -87.6 ...
 $ end_lat           : num  41.9 41.9 41.9 41.9 42 ...
 $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
 $ member_casual     : chr  "member" "member" "member" "member" ...

> Total_Trips$Trip_Duration <- as.POSIXct(Total_Trips$started_at - Total_Trips$ended_at, format = "%H:%M:%S")

Error in as.POSIXct.default(Total_Trips$started_at - Total_Trips$ended_at, : do not know how to convert 'Total_Trips$started_at - Total_Trips$ended_at' to class “POSIXct”

Upvotes: 0

Views: 159

Answers (1)

lovalery
lovalery

Reputation: 4652

Please find below one solution with the lubridate package:

REPREX:

library(lubridate)
 
started_at <- as_datetime(c("2020-04-26 17:45:14", "2020-04-17 17:08:54", "2020-04-01 17:54:13", "2020-04-07 12:50:19"))
ended_at <- as_datetime(c("2020-04-26 18:12:03", "2020-04-17 17:17:03", "2020-04-01 18:08:36", "2020-04-07 13:02:31"))
(results <- hms::as_hms(ended_at - started_at))
#> 00:26:49
#> 00:08:09
#> 00:14:23
#> 00:12:12

Created on 2021-10-04 by the reprex package (v2.0.1)

If you want to apply this solution to your dataframe, you should write something like this (after installing and loading the lubridate library):

Total_Trips$Trip_Duration <- hms::as_hms(as_datetime(Total_Trips$ended_at) - as_datetime(Total_Trips$started_at))

Upvotes: 0

Related Questions