Search code examples
rtimetranslationlubridate

Format the output of as.period() from lubridate


I currently have a period object with this value :

"35d 17H 15M 28.9999999995343S"

I would like to get a different output which is :

35 days 17 hours 15 minutes 28 seconds

I would like to also be able to format it so the units take a "s" or not depending if the time units > 1 or not.

I already tried to get the attributes of the object with attr(period_object, "unit") but I can't modify the seconds since it seems they are not in the object.

str(as.period(period_object))
Formal class 'Period' [package "lubridate"] with 6 slots
  ..@ .Data : num 29
  ..@ year  : num 0
  ..@ month : num 0
  ..@ day   : num 35
  ..@ hour  : num 17
  ..@ minute: num 15

Here is a sample of data :

library(lubridate)
time1 <- as.POSIXct("2019-01-01 15:12:07")
time2 <- as.POSIXct("2019-02-06 08:27:36")
period_object <- difftime(time2, time1)

as.period(period_object)
[1] "35d 17H 15M 28.9999999995343S"

So the final output I want is : 35 days 17 hours 15 minutes 28 seconds

Anyone got some clues? Thank you.


Solution

  • One way to the seconds:

    period_object %/% dseconds(1) %% 60
    #[1] 28
    

    To get them all this way:

    days    <- period_object %/% ddays(1)
    hours   <- period_object %/% dhours(1) %% 24
    minutes <- period_object %/% dminutes(1) %% 60
    seconds <- period_object %/% dseconds(1) %% 60