R convert character "111213" into time "11:12:13".
strptime("111213", format="%H%m%s")
gives NA
and
strptime("111213", "%H%m%s")
gives 1970-01-01 01:00:13 CET
R convert character "111213" into time "11:12:13".
strptime("111213", format="%H%m%s")
gives NA
and
strptime("111213", "%H%m%s")
gives 1970-01-01 01:00:13 CET
I think the canonical answer would be as in my comment:
format(strptime("111213", format="%H%M%S"), "%H:%M:%S")
#[1] "11:12:13"
where you can read ?strptime
for all the details. format
is a generic function, and in this specific case we are using format.POSIXlt
.
Another solution is to merely play with string:
paste(substring("111213", c(1,3,5), c(2,4,6)), collapse = ":")
#[1] "11:12:13"
This makes sense because your input is really not a Date-Time: there is no Date.
We can use
library(chron)
times(gsub("(.{2})(?=\\d)", "\\1:", "111213", perl = TRUE))
#[1] 11:12:13
To manipulate time, you can use hms
package.
By default, it working with %H:%M;%S
(or %X
format).
For you specifique time format ("111213"
), you need to go through base
function as.difftime
hms::as.hms(as.difftime("111213", format = "%H%M%S"))
#> 11:12:13
So if we incorporate also date in similar "integer" format we can obtain command :
strptime("20181017 112233", format="%Y%m%d %H%M%S")