rposixctstrptimeas.dateposixlt

Problem with changing format of date and time in R


I am having a problem with date & time format in R.

My R code is having the format: "%Y%m%d %H%M%OS". For example: "20170929 20:59:56.149"

Time in my case is character variable.

I am trying to write a R code where type of format will be converted into the format "%Y-%m-%d %H:%M:%OS"

(data <- strptime(data$time, 
                    format = "%Y-%m-%d  %H:%M:%OS", 
                    tz = "GMT")) 

or for example

data$time <- as.POSIXct(data$time, format = "%Y-%m-%d  %H:%M:%OS")

But, I am getting NA. What could this be caused by? Do you have any idea how to fix it? Thank you in advance for your help!


Solution

  • From the manual help(strftime): If the specified time is invalid (for example ‘"2010-02-30 08:00"’) all the components of the result are ‘NA’.

    Furthermore, if you want to manipulate your output format of a date you need the date stored as a Date-class (illustration of @izyda's comments).

    First, reformat your date to make it easier to manipulate:

    data <- "20170929 20:59:56.149"
    dat_new <- paste( paste( substr(data, 1, 4), 
       substr(data, 5, 6), substr(data, 7, 8), sep="-" ), 
       substr(data, 10,nchar(data)) )
    dat_new
    [1] "2017-09-29 20:59:56.149"
    

    Then, change the class to Date:

    dat_cor <- as.POSIXct( dat_new, tz="GMT" )
    dat_cor
    [1] "2017-09-29 20:59:56 GMT"
    class(dat_new)
    [1] "character"
    class(dat_cor)
    [1] "POSIXct" "POSIXt"
    

    Finally, choose your output format:

    strftime( dat_cor, format="%m/%d/%Y %H:%M:%OS3", tz="GMT" )
    [1] "09/29/2017 20:59:56.148"
    # or
    strftime( dat_cor, format="%Y-%d-%m %H:%M:%OS3", tz="GMT" )
    [1] "2017-29-09 20:59:56.148"