繁体   English   中英

理解R中的日期/时间(POSIXc和POSIXct)

[英]understanding dates/times (POSIXc and POSIXct) in R

我正在读表,它包含描述时间戳的字符串。 我只想将字符串转换为内置日期时间类型...

R> Q <- read.table(textConnection('
               tsstring
1 "2009-09-30 10:00:00"
2 "2009-09-30 10:15:00"
3 "2009-09-30 10:35:00"
4 "2009-09-30 10:45:00"
5 "2009-09-30 11:00:00"
'), as.is=TRUE, header=TRUE)
R> ts <- strptime(Q$tsstring, "%Y-%m-%d %H:%M:%S", tz="UTC")

如果我尝试将datetime列存储到data.frame中,我会收到一个奇怪的错误:

R> Q$ts <- ts
Error in `$<-.data.frame`(`*tmp*`, "ts", value = list(sec = c(0, 0, 0,  : 
  replacement has 9 rows, data has 5

但如果我通过data.frame中的数字表示,它可以工作......

R> EPOCH <- strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC")
R> Q$minutes <- as.numeric(difftime(ts, EPOCH, tz="UTC"), units="mins")
R> Q$ts <- EPOCH + 60*Q$minutes

了解情况有什么帮助?

strptime返回类POSIXlt ,你需要数据框中的POSIXct

R> class(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt"  "POSIXlt"
R> class(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt"  "POSIXct"

POSIXct类表示自1970年初以来作为数字向量的(带符号)秒数。 POSIXlt类是一个名为sec,min,hour,mday,mon,year等的向量的命名列表。

R> unclass(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
$sec
[1] 0
$min
[1] 0
$hour
[1] 10
$mday
[1] 30
$mon
[1] 8
$year
[1] 109
$wday
[1] 3
$yday
[1] 272
$isdst
[1] 0
attr(,"tzone")
[1] "UTC"

R> unclass(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] 1.254e+09
attr(,"tzone")
[1] "UTC"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM