firmo23
firmo23

Reputation: 8404

Recognize date-time format in R

I have a column with dates in R which is like : 2020-01-03T21:04:18.907Z . Im not sure what kind of date format should I use in order to convert it to a date that I can use. Im not sure what this T21 and 907Z mean.

I try something like:

dtparts = t(as.data.frame(strsplit("2020-01-03T21:04:18.907Z",' ')))
row.names(dtparts) = NULL
library(chron)
thetimes = chron(dates=dtparts[,1],times=dtparts[,1],
                                    format=c('y-m-d','h:m:s'))

but I get:

Error in convert.dates(dates., format = format[[1]], origin. = origin.) : 
  format y-m-d may be incorrect
In addition: Warning message:
In convert.dates(dates., format = format[[1]], origin. = origin.) :
  NAs introduced by coercion

Upvotes: 2

Views: 983

Answers (2)

akrun
akrun

Reputation: 887118

We can convert it to correct format with format

library(lubridate)
dt <- ymd_hms("2020-01-03T21:04:18.907Z")
chron(dates = format(dt, '%Y-%m-%d'), time = format(dt, "%H:%M:%S"), 
        format = c('y-m-d', 'h:m:s'))
#[1] (20-01-03 21:04:18)

Upvotes: 2

alan ocallaghan
alan ocallaghan

Reputation: 3038

Try this:

lubridate::ymd_hms("2020-01-03T21:04:18.907Z")
# [1] "2020-01-03 21:04:18 UTC"

Upvotes: 1

Related Questions