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

时间:2016-02-07 15:02:49

标签: r posixct posixlt

我遇到了在格式化日期和时间(包含毫秒)中加入毫秒的问题。

描述: 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"

以上的输出会给我&#34; 2014-12-22 15:10:41.8 IST&#34; 。 但是,对于毫秒8和80,它也会提供相同的输出&#34; 2014-12-22 15:10:41.8 IST&#34;

另外,如果我使用格式=&#34;%Y-%m-%d%H:%M:%OS3&#34;我得到NA。

1 个答案:

答案 0 :(得分:1)

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

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))