Convert date time to a formatted time string

biocyberman picture biocyberman · Sep 4, 2014 · Viewed 21.3k times · Source

I don't know why it doesn't work. Here is my code:

> t <- hms("14:11:49")
> t
[1] "14H 11M 49S"
t <- t + minutes(3)
> format(t, format="%H:%M:%S")
[1] "14H 14M 49S"
# Expected output: "14:14:49"

Update:

Currently I found this solution, but I hope there is a more elegant one:

t <- hms("14:11:49") # example period object
sprintf("%s:%s:%s", hour(t), minute(t), second(t))
#"14:11:49"

Answer

zx8754 picture zx8754 · Sep 4, 2014

Not sure why you 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:

t <- hms("14:11:49")
t
#[1] "14H 11M 49S"
t <- t + minutes(3)
t
#[1] "14H 14M 49S"

paste(hour(t),minute(t),second(t),sep=":")
#[1] "14:14:49"

Benchmark output:

op <- microbenchmark(
  Use_paste=paste(hour(t),minute(t),second(t),sep=":"),
  Use_sprintf=sprintf("%s:%s:%s", hour(t), minute(t), second(t)),
  times=1000000L)
op

# Unit: microseconds
# expr    min     lq median     uq      max neval
# Use_paste 28.072 31.695 32.601 33.506 44253.42 1e+06
# Use_sprintf 29.582 33.807 34.412 35.619 44367.52 1e+0