Reputation: 792
I am trying to get the difference between two times in R.
For example, time difference between two times: "03:15" and "01:40" will be 1 hour 35 minutes.
I tried the following code in R:
difftime("03:15", "01:40", tz="", units = "secs")
But I am getting the following error:
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
Any help will be highly appreciated.
Upvotes: 2
Views: 907
Reputation: 50668
You can use strptime
to convert to POSIXct
:
t0 <- "03:15";
t1 <- "01:40";
# Time difference in seconds
difftime(strptime(t0, format = "%H:%M"), strptime(t1, format = "%H:%M"), units = "secs");
#Time difference of 5700 secs
# Time difference in minutes
difftime(strptime(t0, format = "%H:%M"), strptime(t1, format = "%H:%M"), units = "mins");
#Time difference of 95 mins
Upvotes: 3
Reputation: 2995
You could try to convert your characters in the POSIXct format first:
difftime(as.POSIXct("03:15",format="%H:%M"),
as.POSIXct("01:40",format="%H:%M"),
tz="", units = "mins")
Upvotes: 1