1

I have a variable in drtn format that looks like this:

f <- structure(c(223, 35, 3, 16, 2, 183, 95, 146, 38, 30), class = "difftime", units = "secs")

< drtn> 223 secs, 35 secs, 3 secs, 16 secs, 2 secs, 183 secs, 95 secs, 146 secs, 38 secs

I want to convert it to a time format like HMS or 00:00:00.

I want to avoid using the as_date function as this will provide the date in addition to the time but I am just looking for it to be in the HMS format similar to this:

< time> 00:03:43, 00:00:35, 00:00:03, 00:00:16, 00:00:02, 00:03:03, 00:01:35
...

Thank you for your Help!

ZachW
  • 19
  • 1
  • 6
  • please use ```dput() ``` to make a reproducible exemple out our data, then we can solve, you can finds something similar here : https://stackoverflow.com/questions/27312292/convert-seconds-to-days-hoursminutesseconds – FrakTool May 31 '20 at 22:32
  • here is an example of the code. Will update my original question with it. f <- structure(c(223, 35, 3, 16, 2, 183, 95, 146, 38, 30), class = "difftime", units = "secs") – ZachW May 31 '20 at 22:44
  • Possible duplicate https://stackoverflow.com/questions/27312292/convert-seconds-to-days-hoursminutesseconds – Ronak Shah Jun 01 '20 at 00:30

1 Answers1

3

One option is to convert the seconds to period and change it to hms

library(lubridate)    
hms::hms(seconds_to_period(df1$col1))
#00:03:43
#00:00:35
#00:00:03
#00:00:16
#00:00:02
#00:03:03
#00:01:35
#00:02:26
#00:00:38

Or with dplyr

library(dplyr)
library(data.table)
df1 %>% 
   mutate(col2 = as.ITime(hms::hms(seconds_to_period(col1))))
# A tibble: 9 x 2
#  col1     col2    
#  <drtn>   <ITime> 
#1 223 secs 00:03:43
#2  35 secs 00:00:35
#3   3 secs 00:00:03
#4  16 secs 00:00:16
#5   2 secs 00:00:02
#6 183 secs 00:03:03
#7  95 secs 00:01:35
#8 146 secs 00:02:26
#9  38 secs 00:00:38

data

df1 <- tibble(col1 = as.difftime(c(223, 35, 3, 16, 2, 183, 95, 146, 38), units = "secs"))
akrun
  • 874,273
  • 37
  • 540
  • 662