将以分:秒:毫秒为单位的字符串时间转换为数字秒

问题描述 投票:0回答:2

我想以上面的格式转换一列字符串时间,例如

"1:25:499"
,我只是想以秒为单位作为输出时间(浮动)
85.499
.

我尝试设置

options(digits.secs =3)
并运行
strptime(df$times, "%OSn")
以将其转换为中间形式,然后转换为固定秒数浮点数。

有什么想法吗?

r time
2个回答
1
投票

你可以用

":"
拆分字符串,然后乘以并求和组件编号:

c("1:25:499", "3:09:004") |>
  strsplit(":") |>
  sapply(\(x) sum(as.numeric(x) * c(60, 1, 1/1000)))
# 85.499 189.004

似乎应该有一种方法可以通过强制为

"difftime"
,然后是
"double"
来做到这一点,但我找不到一个保留毫秒的方法。


1
投票

这是将最后一个冒号转换为句点,然后使用 lubridate 包将字符串转换为秒的解决方案。

library(magrittr)
library(lubridate)

#replace the last colon with a period
time_with_period <- sub(":(\\d+?)$", "\\.\\1", "1:25:499")

#convert from string to a period and
# then into seconds
answer <- ms(time_with_period) %>% period_to_seconds()
answer
© www.soinside.com 2019 - 2024. All rights reserved.