3

我在格式化具有毫秒的日期和时间时遇到了问题。

说明: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。

4

1 回答 1

1

我们可以使用sprintf将列粘贴在一起,因为使用 修改“毫秒”列的格式更容易sprintf。然后,使用 . 转换为 datetime 类strptime

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))
于 2016-02-07T15:56:00.057 回答