1

我在此页面上遇到了一个类似的问题:

R中行之间的日期时间差异

这是我的数据的一个非常小的片段:

DT  
29/07/12 20:05:01   
29/07/12 20:20:59   
30/07/12 02:42:08 
30/07/12 02:53:17 
30/07/12 02:53:18 
30/07/12 02:53:19 

我想做与这个人问的相同的事情,即计算 R 中后续行之间的时间差(增量时间)。时间戳存储在数据框中,时间为日期时间(日/月/年时:分:秒)。

这段代码是好心建议的,并且大部分时间都可以使用,除了时间间隔跨越几天,然后我得到大量不正确的数字(例如 29/07/12 20:20:59 和 30/07/12 之间的 31472469 秒02:42:08。

c_time <- as.POSIXlt( mydf$c_time )
c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])

有没有人有什么建议?

谢谢!

4

1 回答 1

0

最好明确格式,否则您必须仔细阅读默认选项中发生的情况:

mydf <- read.table(text="c_time
29/07/12 20:05:01  
29/07/12 20:20:59  
30/07/12 02:42:08
30/07/12 02:53:17
30/07/12 02:53:18
30/07/12 02:53:19", sep=",", row.names=NULL, header=T)
c_time <- as.POSIXlt( mydf$c_time, format="%d/%m/%y %H:%M:%S")
c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])

##Time differences in secs
##[1]     1     1   669 22869   958
于 2016-04-11T03:34:00.910 回答