2012-09-26 22 views
9

我试图减去含有以下列格式日期时间信息2个字符载体:ř查找YYYY-MM-DD HH以秒时间差:MM:SS.MMM格式

> dput(train2) 

structure(list(time2 = c("2011-09-01 23:44:52.533", "2011-09-05 12:25:37.42", 
"2011-08-24 12:56:58.91", "2011-10-25 07:18:14.722", "2011-10-25 07:19:51.697" 
), time3 = c("2011-09-01 23:43:59.752", "2011-09-05 12:25:01.187", 
"2011-08-24 12:55:13.012", "2011-10-25 07:16:51.759", "2011-10-25 07:16:51.759" 
)), .Names = c("time2", "time3"), row.names = c(NA, 5L), class = "data.frame") 

I”已经在zooas.Dateas.POSIXct等玩过,并尝试找到正确的代码来减去2个日期时间对象,并在几秒钟内得到答案,但没有运气。

我会很感激任何建议。

回答

12

易peasy:

R> now <- Sys.time() 
R> then <- Sys.time() 
R> then - now 
Time difference of 5.357 secs 
R> class(then - now) 
[1] "difftime" 
R> as.numeric(then - now) 
[1] 5.357 
R> 

并为您的数据:

R> df 
        time2     time3 
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752 
2 2011-09-05 12:25:37.42 2011-09-05 12:25:01.187 
3 2011-08-24 12:56:58.91 2011-08-24 12:55:13.012 
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759 
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759 
R> df$time2 <- strptime(df$time2, "%Y-%m-%d %H:%M:%OS") 
R> df$time3 <- strptime(df$time3, "%Y-%m-%d %H:%M:%OS") 
R> df 
        time2     time3 
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752 
2 2011-09-05 12:25:37.420 2011-09-05 12:25:01.187 
3 2011-08-24 12:56:58.910 2011-08-24 12:55:13.012 
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759 
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759 
R> df$time2 - df$time3 
Time differences in secs 
[1] 52.781 36.233 105.898 82.963 179.938 
attr(,"tzone") 
[1] "" 
R> 

,并重新添加为数字数据帧:

R> df$dt <- as.numeric(df$time2 - df$time3) 
R> df 
        time2     time3  dt 
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752 52.781 
2 2011-09-05 12:25:37.420 2011-09-05 12:25:01.187 36.233 
3 2011-08-24 12:56:58.910 2011-08-24 12:55:13.012 105.898 
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759 82.963 
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759 179.938 
R> 
+0

非常感谢你。我从来没有得到过我自己的。日期时间的东西对我来说是一个“未知的未知”(从Don Rumsfeld借用)。 – screechOwl

+11

值得指出的是,你可以使用'difftime'(现在,单位=“secs”)或'difftime(现在单位=“分钟”)强制时间差异成为一个特定的时间单位'等等...见'?difftime' – thelatemail

+0

@screechOwl:就像很多事情R一样,它有时需要一些头部划痕和前额撞击,但它非常非常强大。绝对值得学习。 –

14
> x1<-"2013-03-03 23:26:46.315" 
> x2<-"2013-03-03 23:31:53.091" 
> x1 <- strptime(x1, "%Y-%m-%d %H:%M:%OS") 
> x2 <- strptime(x2, "%Y-%m-%d %H:%M:%OS") 
> x1 
[1] "2013-03-03 23:26:46" 
> x2 
[1] "2013-03-03 23:31:53" 

我跟着@Dirk Eddelbuettel的回答,但我是losi精确度。我怎样才能让R不被切断第二部分?

值得庆幸的是(strptime的人),我回答我自己的问题:

op <- options(digits.secs = 3) 

应用此设置的精度将被使用之后。

http://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html

的belowe可能是有用的,如果你想获得在几秒钟的差别,而是要分:

> as.numeric(x2-x1,units="secs") 
[1] 306.776