difftime between days not woking

I have a data frame for bike trip for a city, I have two columns, one for the start date-time and other for the end date-time, the tripduration is a calculated column using the difftime function.

bikeRides$tripduration <- difftime(bikeRides$ended_at, bikeRides$started_at, units ="hours")

The problem is. whatever time unit I use, when the trip goes for one day to another, the time it calculates is more than a day as you can see in the second column, that being a aprox 20 minutes trip

I can't seem to make this not work...

s_t1 <- "2020-07-24 23:56:30"
s_t2 <- "2020-07-25 00:20:17"

l_t1 <- as.POSIXlt(s_t1)
l_t2 <- as.POSIXlt(s_t2)
difftime(l_t2,l_t1,units = "hours")
# Time difference of 0.3963889 hours
c_t1 <- as.POSIXct(s_t1)
c_t2 <- as.POSIXct(s_t2)
difftime(c_t2,c_t1,units = "hours")
#Time difference of 0.3963889 hours

perhaps to help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

1 Like

If this not work for you, try using as.duration() from {lubridate} package.


bikeRides <- bikeRides %>% 
    mutate(tripduration = as.duration(started %--% ended)/dhours(1))
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.