'Time difference between two times in R

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.

r


Solution 1:[1]

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

Solution 2:[2]

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")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maurits Evers
Solution 2 kluu