Welcome to SO! In general please post a minimal reproducible example of the relevant parts of your dataset using dput()
or similar.
The <chr>
in your output means that your columns are a character vector rather than date time.
As pointed out in the comments by jay.sf, difftime()
can parse character vectors in some formats, and it should be able to parse the single example given in your post.
Nevertheless, in general it is better to store datetimes as one of the built-in datetime classes, i.e. either POSIXct
or POSIXlt
, rather than to rely on implicit coercion. To convert them:
all_trips$started_at <- as.POSIXct(all_trips$started_at)
all_trips$ended_at <- as.POSIXct(all_trips$ended_at)
# Calculate diff time
all_trips$ride_length <- difftime(
all_trips$ended_at,
all_trips$started_at,
units = "secs"
)
You will get an error if the conversion does not work:
as.POSIXct(c("2019-04-01 00:02:22", "not a valid date time"))
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
This is the same error you will get if you try to use difftime()
with a character vector that is not unambiguously a datetime.
This post is a useful discussion of R's internal handling of date/time classes.