Skip to content

Commit

Permalink
fix: sub-second value parsing accurately
Browse files Browse the repository at this point in the history
  • Loading branch information
eitsupi committed Nov 14, 2024
1 parent 45e8585 commit cff8e20
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
20 changes: 10 additions & 10 deletions R/parse.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
#' parse_hms("12:34:56")
#' parse_hms("12:34:56.789")
parse_hms <- function(x) {
as_hms(parse_time(x, format = "%H:%M:%OS"))
parsed <- strptime(as.character(x), format = "%H:%M:%OS")
hms(
seconds = parsed$sec,
minutes = parsed$min,
hours = parsed$hour
)
}

#' @rdname parse_hms
Expand All @@ -24,14 +29,9 @@ parse_hms <- function(x) {
#' @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"
parsed <- strptime(as.character(x), format = "%H:%M")
hms(
minutes = parsed$min,
hours = parsed$hour
)
}
1 change: 1 addition & 0 deletions tests/testthat/test-parse.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ test_that("parse_hms", {
expect_equal(parse_hms("12:34:56.789"), hms(56.789, 34, 12))
expect_equal(parse_hms(NA), hms(NA))
expect_equal(parse_hms(c("12:34:56", NA)), as_hms(c(hms(56, 34, 12), hms(NA))))
expect_identical(parse_hms("23:59:59.999999999"), as_hms(86399.999999999))
})

test_that("parse_hm", {
Expand Down

0 comments on commit cff8e20

Please sign in to comment.