简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM