Home > Back-end >  How to convert difftime to string "X hours Y minutes Z seconds"
How to convert difftime to string "X hours Y minutes Z seconds"

Time:11-16

I want to print a difftime object as a string like "X hours Y minutes Z seconds".

So instead of printing e.g. "1.034167 hours" I would like to see "1 hour 2 minutes 3 seconds".

library(hms)
difftime(hms(11, 02, 03), hms(10, 00, 00))
Time difference of 3.033611 hours

magicfunction(difftime(hms(11, 02, 03), hms(10, 00, 00)))
1 hour 2 minutes 3 seconds

CodePudding user response:

It may be easier to convert to period if the units is seconds

library(lubridate)
seconds_to_period(difftime(hms::hms(11, 02, 03), 
       hms::hms(10, 00, 00), units = 'sec'))

CodePudding user response:

library(lubridate)

diff <- hms("11:02:03") - hms("10:00:00")

diff
# [1] "1H 2M 3S"

paste(diff$hour, "hours", diff$minute, "minutes", diff$second, "seconds")
# [1] "1 hours 2 minutes 3 seconds"
  •  Tags:  
  • r
  • Related