Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save hadley/1dab5802ce844a5bd731 to your computer and use it in GitHub Desktop.

Select an option

Save hadley/1dab5802ce844a5bd731 to your computer and use it in GitHub Desktop.
Go style date formats for R
library("stringi")
ref <- ISOdatetime(2006, 01, 02, 15, 4, 0, "MST")
formats <- c("%H", "%Y", "%y", "%b", "%B", "%m", "%d", "%e", "%a",
"%A", "%I", "%l", "%p", "%Z", "%z", "%M", "%S")
# Must manually respecify TZ because strftime doesn't use the time zone
# stored in ref
conv <- vapply(formats, function(x) strftime(ref, x, tz = "MST"), character(1))
make_format <- function(x) {
stringi::stri_replace_all_regex(x, unname(conv), names(conv), vectorize_all = FALSE)
}
parse_time <- function(x, format) {
as.POSIXct(strptime(x, make_format(format)))
}
parse_self <- function(x) parse_time(x, x)
parse_self("02 Jan 06 15:04 -0700")
make_format("Jan 2, 2006")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment