R中的字符串到毫秒的转换

时间:2018-11-05 06:43:59

标签: r datetime

我有一个包含时间的字符串 timedata <- "08:39:41:759:520"我想将此日期字符串值转换为毫秒格式。

注意: 我尝试使用以下命令: as.POSIXct(timedata)

它引发以下错误: Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format

我该如何解决并将数据转换为毫秒/微秒格式

1 个答案:

答案 0 :(得分:2)

您需要先修复您的输入字符串。我假设它是hours:minutes:seconds:milliseconds:microseconds

timedata <- "08:39:41:759:520"

#replace last two :
timedata <- gsub(":(?=\\d*$)", ".", 
     gsub(":(?=\\d*$)", "", 
          timedata, 
          perl = TRUE), 
     perl = TRUE)

#coerce to POSIXct and subtract current date
timedata <- as.numeric(as.POSIXct(timedata, '%H:%M:%OS', tz='UTC')) - 
  as.numeric(as.POSIXct(Sys.Date()))

#this is a floating point number, print digits of interest (following digits can't be zero)
sprintf("%.6f",timedata)
#[1] "31181.759520"