R/parse.R

Defines functions parse_time parse_hm parse_hms

Documented in parse_hm parse_hms

#' Parsing hms values
#'
#' @description
#' These functions convert character vectors to objects of the [hms] class.
#' `NA` values are supported.
#'
#' `parse_hms()` accepts values of the form `"HH:MM:SS"`, with optional
#' fractional seconds.
#' @param x A character vector
#' @return An object of class [hms].
#'
#' @export
#' @examples
#' parse_hms("12:34:56")
#' parse_hms("12:34:56.789")
parse_hms <- function(x) {
  as_hms(parse_time(x, format = "%H:%M:%OS"))
}

#' @rdname parse_hms
#' @description
#' `parse_hm()` accepts values of the form `"HH:MM"`.
#' @export
#' @examples
#' parse_hm("12:34")
parse_hm <- function(x) {
  as_hms(parse_time(x, format = "%H:%M"))
}

parse_time <- function(x, format) {
  difftime(
    strptime(as.character(x), format = format),
    strptime("0:0:0", format = "%X"),
    units = "secs",
    tz = "UTC"
  )
}

Try the hms package in your browser

Any scripts or data that you put into this service are public.

hms documentation built on March 31, 2023, 11:09 p.m.