user3642360
user3642360

Reputation: 792

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.

Upvotes: 2

Views: 907

Answers (2)

Maurits Evers
Maurits Evers

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

kluu
kluu

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

Related Questions