r - Parse time elapsed / time span / duration with several different formats -
i need parse time spans several different formats, including days, hours, minutes, seconds.ms, separated :
: %os
, %h:%os
, %h:%m:%os
or %d:%h:%m:%os
. example:
x <- c("28.6575", "1:14.0920", "1:5:38.1230", "5:23:59:38.7211")
the first idea comes mind using strptime
parse given strings date. approach not work strings not contain parts of time span. possible turn parts of format string being optional?
strptime("5:23:59:38.7211", "%d:%h:%m:%os") # [1] "2015-08-05 23:59:38" strptime("1:5:38.1230", "%d:%h:%m:%os") # [1] na # wanted: "2015-08-01 01:05:38"
a different approach turn formatted values seconds (e.g. 1:14.0920 ~~> 74.0920 secs
). however, unable find convenient way using r.
here's expanded version of @konrad rudolph's comment:
# split time spans different time elements l <- strsplit(x, ":") # pad vector leading zeros. here 4 maximum number of time elements m <- sapply(l, function(x) as.numeric(c(rep(0, 4 - length(x)), x))) # convert result desired unit, e.g. seconds m[1 , ] * 24*60*60 + m[2 , ] * 60*60 + m[3 , ] * 60 + m[4 , ] # [1] 28.6575 74.0920 3938.1230 518378.7211
Comments
Post a Comment