如何让POSIXct与==

时间:2016-11-17 18:10:41

标签: r comparison posixct

我注意到==似乎无法使用POSIXct:

a <- structure(c(1466985600, 1464652800, 1464652800, 1464652800, 1472428800, 
1466985600, 1468195200, 1472428800, 1472428800, 1474848000, 1464652800, 
1468195200, 1476057600, 1464652800, 1472428800, 1472428800, 1460332800, 
1460332800, 1460332800, 1460332800), class = c("POSIXct", "POSIXt"
), tzone = "UTC")

a
  

[1]&#34; 2016-06-27 UTC&#34; &#34; 2016-05-31 UTC&#34; &#34; 2016-05-31 UTC&#34; &#34; 2016-05-31 UTC&#34; &#34; 2016-08-29 UTC&#34; &#34; 2016-06-27 UTC&#34; &#34; 2016-07-11 UTC&#34;   &#34; 2016-08-29 UTC&#34;        [9]&#34; 2016-08-29 UTC&#34; &#34; 2016-09-26 UTC&#34; &#34; 2016-05-31 UTC&#34; &#34; 2016-07-11 UTC&#34; &#34; 2016-10-10 UTC&#34; &#34; 2016-05-31 UTC&#34; &#34; 2016-08-29 UTC&#34;   &#34; 2016-08-29 UTC&#34;       [17]&#34; 2016-04-11 UTC&#34; &#34; 2016-04-11 UTC&#34; &#34; 2016-04-11 UTC&#34; &#34; 2016-04-11 UTC&#34;

table(a=="2016-06-27")
FALSE 
   20
table(a=="2016-06-27 UTC")
FALSE 
   20
table(a==as.POSIXct("2016-06-27 UTC"))
FALSE 
   20
table(a==as.POSIXct("2016-06-27"))
FALSE 
   20
a[a=="2016-06-27"]
character(0)

我怎样才能让它发挥作用?

这样可行,但我真的希望它不是我唯一的选择:

a[a==1466985600]
[1] "2016-06-27 UTC" "2016-06-27 UTC"

1 个答案:

答案 0 :(得分:3)

除非在format参数中指定,否则时区必须是分开的。您的代码会在字符串中嵌入时区,但默认格式为"%Y-%m-%d""%Y/%m/%d",因此时区会被截断,默认为当前区域设置。我们可以找到aattr()的时区,因为它是a的属性。

table(a == as.POSIXct("2016-06-27", tz = attr(a, "tzone")))

# FALSE  TRUE 
#    18     2