如何以毫秒解析日期和时间,分布在多个列中?

How to parse date and time with milliseconds, spread across multiple columns?

我在将毫秒纳入具有毫秒的格式日期和时间时遇到问题。

说明: csv 中的日期格式分别分布在前 3 列 2014/12/22,14:48:51,800 作为日期、时间和毫秒。 所以,我基本上将它们合并为 1。在这里,为了说明,我取了数据帧的 1 行

temp
#[1] "2014/12/22" "14:48:51"   "800" 

temp <- gsub("/","-",paste(temp[1],paste(temp[2],temp[3],sep="."),sep=" "))
#[1] "2014-12-22 14:48:51.800" 

然后,设置选项

op <- options(digits.secs = 3)
options(op)
Date_time <- as.POSIXlt(strptime(temp, format="%Y-%m-%d %H:%M:%OS"))
#[1] "2014-12-22 14:48:51.8 IST"

上面的输出会给我 "2014-12-22 15:10:41.8 IST" 。 但是,对于毫秒 8 和 80,它也给出相同的输出“2014-12-22 15:10:41.8 IST”

另外,如果我使用 format="%Y-%m-%d %H:%M:%OS3" 我会得到 NA。

我们可以使用 sprintf 将列粘贴在一起,因为使用 sprintf 更容易修改 'millisec' 列的格式。然后,使用 strptime.

转换为日期时间 class
op <- options(digits.secs = 3)
strptime(sprintf("%s %s.%03d", temp[,1], temp[,2], 
          temp[,3]), format = '%Y/%m/%d %H:%M:%OS')
#[1] "2014-12-22 14:48:51.800 IST" "2014-12-22 14:48:51.008 IST" 
#[3] "2014-12-22 14:48:51.080 IST"

数据

temp <- structure(list(date = c("2014/12/22", "2014/12/22",
    "2014/12/22"), time = c("14:48:51", "14:48:51", "14:48:51"),
   millisec = c(800L, 8L, 80L)), .Names = c("date", 
  "time", "millisec"), class = "data.frame", row.names = c(NA, -3L))