lubridate::duration("minutes") returns an error when duration less than 60 seconds

Viewed 100

I am timing events that are usually of multiple minutes duration but occasionally an event will be less than 60 seconds and lubridate::duration() returns an erroneous value.

I can fix this problem with an IF and 2 duration functions by checking for time differences greater than or less than 60 seconds but it seems such an inelegant method.

library(lubridate)
for (x in c(59, 60)) {
  startTime <- Sys.time()
Sys.sleep(x)
print(duration(as.numeric(Sys.time() - startTime), "minutes" ))
}

[1] "3543.86645793915s (~59.06 minutes)"
[1] "60.0540399551392s (~1 minutes)"

I just want time less than 60 seconds in decimal minutes or just seconds. Thank you.

1 Answers

I am supposing your interval of time are objects of class difftime. If it is like that, see the next script:

#Create object difftime
a <- Sys.time()
b <- Sys.time()
DELTA_TIME <- b - a
#print the duration
print(duration(as.numeric(DELTA_TIME,units='mins'),units='minutes'))

See that this way of printing the duration will accept any object of class difftime. The important thing is the argument unit='mins' in the function as.numeric

Related