Search code examples
rdatetime-formatdate-conversion

R convert character "111213" into proper time which is "11:12:13"


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


Solution

  • 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.