Created
December 13, 2016 10:11
-
-
Save arnauldvm/1e87f90f67d672fa7614a5e1ded5d037 to your computer and use it in GitHub Desktop.
parse a string representing a duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
parse_duration_to_ms = function(string) { # e.g. "1w 2d5h15m 08.24s", "0.000045s" | |
opt_sep_re = "\\h*" | |
re = paste0("^", | |
"(?:(?<weeks>\\d+)w)?", opt_sep_re, | |
"(?:(?<days>\\d+)d)?", opt_sep_re, | |
"(?:(?<hours>\\d+)h)?", opt_sep_re, | |
"(?:(?<minutes>\\d+)m)?", opt_sep_re, | |
"(?:(?<seconds>\\d+)(?:\\.(?<milliseconds>\\d*))?s)?", | |
"$") | |
data = parseLines(re, string) | |
l=nchar(as.character(data$milliseconds)) | |
if (l<3) data$milliseconds = paste0(data$milliseconds, paste(rep("0", 3-l), collapse="")) | |
if (l>3) data$milliseconds = sub("(\\d{3})(\\d+)", "\\1.\\2", data$milliseconds) | |
data = data.frame(t(apply(data, MARGIN=1, FUN=function(x) ifelse(x=='', 0, as.numeric(x))))) | |
1000*(60*(60*(24*(7*data$weeks+data$days)+data$hours)+data$minutes)+data$seconds)+data$milliseconds | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment