我需要解析几种不同格式的时间跨度,包括天、小时、分钟、秒.ms,用:
分隔:%OS
, % H:%OS
、%H:%m:%OS
或 %d:%H:%m:%OS
。例如:
x <- c("28.6575", "1:14.0920", "1:5:38.1230", "5:23:59:38.7211")
首先想到的是使用 strptime
将给定的字符串解析为日期。此方法不适用于不包含时间跨度所有部分的字符串。是否可以将部分格式字符串变成可选的?
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"
另一种方法是将格式化值转换为秒(例如 1:14.0920 ~~> 74.0920 secs
)。但是,我找不到使用 R 来执行此操作的便捷方法。
最佳答案
这是@Konrad Rudolph 评论的扩展版本:
# split time spans into their different time elements
l <- strsplit(x, ":")
# pad vector with leading zeros. Here 4 is the maximum number of time elements
m <- sapply(l, function(x) as.numeric(c(rep(0, 4 - length(x)), x)))
# convert result to 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
关于r - 用几种不同的格式解析耗时/时间跨度/持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31829263/