Search code examples
rdatetimetimecol

R - How to extract the time from a datetime column to use for graphing


I have a column named time that contains the date and time, listed in this format ex: 03/20/2016 14:24:47.153. I want to extract the time portion to be used to produce a line graph (so I will like a comprehensive x axis time interval). How can I do this?


Solution

  • We can use sub to extract the "time" from the string.

    sub("\\S+\\s+", "", str1)
    #[1] "14:24:47.153"
    

    Or convert to Datetime class and then format

    options(digits.secs=3)
    format(strptime(str1, format= "%m/%d/%Y %H:%M:%OS"), "%H:%M:%OS3")
    #[1] "14:24:47.153"
    

    data

    str1 <- "03/20/2016 14:24:47.153"