-2

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

Qbik
  • 5,885
  • 14
  • 62
  • 93
  • 5
    You need `strptime("111213", format="%H%M%S")`. And you can get a list of formatting parameters by checking `?strptime`. `%m` parse the month; `%M` parses the minute. `%S` parses the second. – Psidom Jan 15 '17 at 14:11

4 Answers4

3

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.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • could you please update your solution with `91213` case ? current returns `NA` – Qbik Jan 21 '17 at 21:33
  • @Qbik This does it: `format(strptime(sprintf("%06d", 91213), format="%H%M%S"), "%H:%M:%S")`. If your input is readily a string, make it an integer first: `format(strptime(sprintf("%06d", as.integer("91213")), format="%H%M%S"), "%H:%M:%S")` – Zheyuan Li Jan 21 '17 at 21:46
3

We can use

library(chron)
times(gsub("(.{2})(?=\\d)", "\\1:", "111213", perl = TRUE))
#[1] 11:12:13
akrun
  • 874,273
  • 37
  • 540
  • 662
3

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
cderv
  • 6,272
  • 1
  • 21
  • 31
  • What is class of output object ? – Qbik Jan 18 '17 at 19:54
  • `hms` package works with *hms* objects wich are also of class *difftime*. The package creates " A simple class for storing time-of-day values" - it is its purpose – cderv Jan 21 '17 at 14:04
0

So if we incorporate also date in similar "integer" format we can obtain command :

strptime("20181017 112233", format="%Y%m%d %H%M%S")
Qbik
  • 5,885
  • 14
  • 62
  • 93