0

I have the following character vector:

times <- c("2020-04-15T03:30:05.197Z", "2020-04-15T03:30:05.366Z", "2020-04-15T03:30:05.530Z")

I need to first convert it to a lubridate datetime object or a POSIXct object - I'm not picky. The following does not work:

as_datetime(link_log$createdAt,
            format = "%Y-%m-%d%T%H:%M:%S")

To be honest, I'm not sure what's going on with the end of each element. What is the .197Z, .366Z, .530Z? I am assuming these are the problem!

Brigadeiro
  • 2,649
  • 13
  • 30

2 Answers2

2

The anytime package was written to make this automatic: no need for format strings or conversions:

R> times <- c("2020-04-15T03:30:05.197Z", "2020-04-15T03:30:05.366Z", 
+             "2020-04-15T03:30:05.530Z")
R> anytime::anytime(times)
[1] "2020-04-15 03:30:05.197 CDT" "2020-04-15 03:30:05.365 CDT" 
[3] "2020-04-15 03:30:05.529 CDT"
R> 

You can pass in character or factor or numeric or ... formats, and as long as the format is sensible and common (i.e. we ignore two-digit years) it should work. It even allows for different formats. It also runs faster than most alternatives requiring a format or hint.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
1

lubridate's ymd_hms seems to work.

options(digits.secs=6)
lubridate::ymd_hms(times)

#[1] "2020-04-15 03:30:05.197 UTC" "2020-04-15 03:30:05.366 UTC" 
#    "2020-04-15 03:30:05.529 UTC"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213