Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parser for RFC 3339 #254

Closed
DavisVaughan opened this issue Oct 7, 2021 · 0 comments · Fixed by #260
Closed

Parser for RFC 3339 #254

DavisVaughan opened this issue Oct 7, 2021 · 0 comments · Fixed by #260

Comments

@DavisVaughan
Copy link
Member

DavisVaughan commented Oct 7, 2021

This is basically an even saner ISO 8601
https://datatracker.ietf.org/doc/html/rfc3339#page-4

It is stricter, and basically just offers 4 formats (plus optional fractional seconds)

%Y-%m-%dT%H:%M:%SZ
%Y-%m-%d %H:%M:%SZ # replace T with space

%Y-%m-%dT%H:%M:%S+00:00 # replace Z with offset from UTC
%Y-%m-%d %H:%M:%S+00:00 # replace T with space

So we can do:

library(clock)
library(rlang)

sys_time_parse_rfc3339 <- function(x, 
                                   ...,
                                   separator = "T",
                                   offset = "Z",
                                   precision = "second") {
  separator <- arg_match0(separator, values = c("T", "t", " "), arg_nm = "separator")
  offset <- arg_match0(offset, values = c("Z", "z", "%z"), arg_nm = "offset")
  format <- paste0("%Y-%m-%d", separator, "%H:%M:%S", offset)
  sys_time_parse(x, ..., format = format, precision = precision)
}

date_time_parse_rfc3339 <- function(x,
                                    ...,
                                    separator = "T",
                                    offset = "Z") {
  x <- sys_time_parse_rfc3339(x, ..., separator = separator, offset = offset, precision = "second")
  as.POSIXct(x, tz = "UTC")
}

foo <- c("2019-09-07T15:14:24Z", "2014-06-02T08:52:46Z", "2014-06-16T08:36:43Z")

date_time_parse_rfc3339(foo)
#> [1] "2019-09-07 15:14:24 UTC" "2014-06-02 08:52:46 UTC"
#> [3] "2014-06-16 08:36:43 UTC"

foo <- c("2019-09-07T15:14:24+01:00", "2014-06-02T08:52:46+01:00", "2014-06-16T08:36:43+01:30")

date_time_parse_rfc3339(foo, offset = "%z")
#> [1] "2019-09-07 14:14:24 UTC" "2014-06-02 07:52:46 UTC"
#> [3] "2014-06-16 07:36:43 UTC"

It nicely doesn't allow for local time in any way, so we can safely return UTC time stamps.

From my understanding in reading the RFC, the only optional part is fractional seconds, so we don't need to try and support a ton of formats that we have to guess through, which I really like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant