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!
CodePudding user response:
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"
CodePudding user response:
I think @izyda has already cleared up the confusion. The format that you include in strptime
is the format of the data that you have, so in this case you use -
x <- "20170929 20:59:56.149"
strptime(x, format = "%Y%m%d %H:%M:%OS", tz = "GMT")
#[1] "2017-09-29 20:59:56 GMT"
The same can be applied to as.POSIXct
.
Alternatively, if you are confused by different formats or tired of referring to ?strptime
you can use lubridate
package. In this case, function ymd_hms
would help.
lubridate::ymd_hms(x)
#[1] "2017-09-29 20:59:56 UTC"