是否有一个很好的方法来处理时间段,如05:30(5分30秒)?
或者,用几秒钟将其转换为整数的最快方法是什么?
我只能转换为日期,并且无法真正找到时间的数据类型.
我和动物园一起使用R.
非常感谢 !
秒是解决这个问题的最好方法.我将Shane的代码改编成了我的目的,这是结果.
# time - time in the format of dd hh:mm:ss
# (That's the format used in cvs export from Alcatel CCS reports)
#
time.to.seconds <- function(time) {
t <- strsplit(as.character(time), " |:")[[1]]
seconds <- NaN
if (length(t) == 1 )
seconds <- as.numeric(t[1])
else if (length(t) == 2)
seconds <- as.numeric(t[1]) * 60 + as.numeric(t[2])
else if (length(t) == 3)
seconds <- (as.numeric(t[1]) * 60 * 60
+ as.numeric(t[2]) * 60 + as.numeric(t[3]))
else if (length(t) == 4)
seconds <- (as.numeric(t[1]) * 24 * 60 * 60 +
as.numeric(t[2]) * 60 * 60 + as.numeric(t[3]) * 60 +
as.numeric(t[4]))
return(seconds)
}
Run Code Online (Sandbox Code Playgroud)
是的,虽然没有'时间'类型,但您可以使用偏移时间:
R> now <- Sys.time()
R> now
[1] "2009-09-07 08:40:32 CDT"
R> class(now)
[1] "POSIXt" "POSIXct"
R> later <- now + 5*60
R> later
[1] "2009-09-07 08:45:32 CDT"
R> class(later)
[1] "POSIXt" "POSIXct"
R> tdelta <- difftime(later, now)
R> tdelta
Time difference of 5 mins
R> class(tdelta)
[1] "difftime"
R>
Run Code Online (Sandbox Code Playgroud)
当您使用zoo包时,您使用POSIXt的是时间索引的标准类型.动物园和更新且也是高度推荐的xts包都可以使用POSIXt,特别是紧凑POSIXct型,用于索引.
xts包具有更多索引功能,Jeff最近根据ISO8601-2004(e)规范添加了间隔解析,并为ISO8601提供了这些参考, 并提供了广泛使用的日期和时间格式标准的常见问题解答.要使用此xts版本,您可能需要在r-forge上切换xts开发快照
[ 编辑: ]另外,关于'转换'的问题:一旦你有了POSIXt/POSIXct类的对象,这很容易,因为它as.numeric()会将POSIXct转换为自纪元以来的(小数)秒.R比POSIX标准更进一步,在这里使用了一个双精度数,所以你得到毫秒精度:
R> options("digits.secs"=6) ## needed so that fractional seconds are printed
R> now <- Sys.time(); difftime(Sys.time(), now)
Time difference of 0.000149 secs
Run Code Online (Sandbox Code Playgroud)
和
R> print(as.numeric(now), digits=15) ## print with digits for sub-second time
[1] 1252374404.22975
R>
Run Code Online (Sandbox Code Playgroud)
正如 Dirk 指出的那样,有一个名为“difftime”的对象,但它不能被添加/减去。
> as.difftime(5, units="mins")
Time difference of 5 mins
> d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
> d
[1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"
> d + as.difftime(5, units="mins")
[1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
[3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
Warning message:
Incompatible methods ("+.POSIXt", "Ops.difftime") for "+"
Run Code Online (Sandbox Code Playgroud)
看来你现在可以这样做:
> as.difftime(5, units='mins')
Time difference of 5 mins
> d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
> d
[1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"
> d + as.difftime(5, unit='mins')
[1] "2003-01-01 00:05:00 GMT" "2003-01-02 00:05:00 GMT"
[3] "2003-01-03 00:05:00 GMT" "2003-01-04 00:05:00 GMT"
> d + as.difftime(5, unit='secs')
[1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
[3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
>
Run Code Online (Sandbox Code Playgroud)
这是最近发布的 R 2.15.0