Convert date time to a formatted time string
Not sure why we need to convert to hms
and back to initial string format. Maybe parse_date_time
function is what you need:
library(lubridate)
myTime <- "14:11:49"
hms(myTime)
#"14H 11M 49S"
POSIXct_myTime <- parse_date_time(myTime,"hms")
format(POSIXct_myTime, format="%H:%M:%S")
#"14:11:49"
EDIT:
We can use paste
:
tt <- hms("14:11:49")
tt
#[1] "14H 11M 49S"
tt <- tt + minutes(3)
tt
#[1] "14H 14M 49S"
paste(hour(tt), minute(tt), second(tt), sep = ":")
#[1] "14:14:49"
Benchmark output:
big <- rep(tt, 10000)
bench::mark(
paste = paste(hour(big), minute(big), second(big), sep = ":"),
sprintf = sprintf("%s:%s:%s", hour(big), minute(big), second(big)),
shosaco = format(Sys.Date() + big, "%H:%M:%S"))
# # A tibble: 3 x 13
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
# <bch:expr> <bch:> <bch:> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm>
# 1 paste 27.7ms 29.8ms 30.9 312.69KB 0 16 0 517ms
# 2 sprintf 29.5ms 42.7ms 23.3 312.69KB 0 12 0 515ms
# 3 shosaco 28.3ms 29.2ms 33.1 2.06MB 0 17 0 514ms
# # ... with 4 more variables: result <list>, memory <list>, time <list>,
# # gc <list>
The proposed solution does not print leading zeros. The following solution seems to be more elegant:
> t <- hms("14:01:49") + minutes(3)
> sprintf("%s:%s:%s", hour(t), minute(t), second(t))
[1] "14:4:49" # looking weird
> format(Sys.Date() + t, "%H:%M:%S")
[1] "14:04:49" # looking better
The problem is that class(t)
is "Period" and the format.Period()
function does not have a parameter for format=
. The t
object is not a standard POSIXt
style object that you may be used to using with format()
. Only the format.POSIXct()
and format.POSIXlt()
functions will behave like that.
So perhaps the easiest thing to do would be to define a helper function to turn the Period
class into POSIXct
. We can do that with:
as.POSIXct.Period <- function(x, start=today()) {
X<-as.interval(x, start);
[email protected]+X@start
}
It's important to note that POSIXct
is a date/time value, not just a time value. So by default we just assume it started at midnight today. But then we can use format in the way you wanted
format(as.POSIXct(t), format="%H:%M:%S")
# [1] "14:11:49"
I must admit I'm not an expert lubridate
user so perhaps I've overlooked an obvious function, but it seems the options for formatting lubridate
classes into "pretty" formats are very limited.