I am writing a small code where i compare two times and find the difference and display it in HH:MM:SS format.
library(magrittr)
library(lubridate)
s1 <- ymd_hms(Sys.time())
s2 <- ymd_hms(Sys.time()) +200
d1 <- seconds_to_period(as.numeric(difftime(s2, s1, units = "secs")));
d2 <-sprintf('%02d:%02d:%02d', hour(d1), minute(d1), second(d1));
d2 [1] "00:03:21"
Another way i am trying is through piping techniques. But here, i am receiving an error.
s1 <- ymd_hms(Sys.time())
s2 <- ymd_hms(Sys.time()) +200
d3 <- difftime(s2, s1, units = "secs") %>% as.numeric() %>% seconds_to_period() %>% sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.))
d3 <- difftime(s2, s1, units = "secs") %>% as.numeric() %>% seconds_to_period() %>% + sprintf('%02d:%02d:%02d', hour(.), minute(.), second(.)) Error in sprintf(., "%02d:%02d:%02d", hour(.), minute(.), second(.)) : 'fmt' is not a character vector
The dot operation seems to not be working for this case. What should I do?
Also, is there better way to implement the time function?