我需要在zoo对象的索引上使用as.Date。有些日期是在BST中,所以当转换时,我在这些条目上(只)损失了一天。我根本不关心一个小时的差异,甚至不关心日期的时间部分,我只想确保显示的日期保持不变。我猜这不是很难,但我做不到。有人能帮帮忙吗?
class(xtsRet)
#[1] "xts" "zoo"
index(xtsRet)
#[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"
class(index(xtsRet))
#[1] "POSIXt" "POSIXct"
index(xtsRet) <- as.Date(index(xtsRet))
index(xtsRet)
#[1] "2007-07-30" "2007-08-30" "2007-09-29" "2007-10-31"可重复性最低的示例(不需要zoo包):
my_date <- as.POSIXct("2007-04-01") # Users in non-UK timezone will need to
# do as.POSIXct("2007-04-01", "Europe/London")
my_date
#[1] "2017-04-01 BST"
as.Date(my_date)
#[1] "2017-03-31"发布于 2012-01-09 21:41:33
您可以对POSIX对象进行偏移,这样它就不会在午夜前后发生变化。1小时(3600秒)应该足够了:
d <- as.POSIXct(c("2007-07-31","2007-08-31","2007-09-30","2007-10-31"))
d
[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"
as.Date(d)
[1] "2007-07-30" "2007-08-30" "2007-09-29" "2007-10-31"
as.Date(d+3600)
[1] "2007-07-31" "2007-08-31" "2007-09-30" "2007-10-31"发布于 2012-01-09 21:39:23
假设我们有以下示例数据:
library(zoo)
x <- as.POSIXct("2000-01-01", tz = "GMT")然后看看这些是不是你想要的:
# use current time zone
as.Date(as.character(x, tz = ""))
# use GMT
as.Date(as.character(x, tz = "GMT"))
# set entire session to GMT
Sys.setenv(TZ = "GMT")
as.Date(x)另外,请尝试用"BST"代替"GMT",并注意关于R News 4/1中的日期和时间的文章。
发布于 2020-04-02 23:55:12
我建议使用as.POSIXlt转换为包装在as.Date中的date对象:
d <- as.POSIXct(c("2007-07-31","2007-08-31","2007-09-30","2007-10-31"))
d
[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"
as.Date(as.POSIXlt(d))
[1] "2007-07-31" "2007-08-31" "2007-09-30" "2007-10-31"实现了与上面的+3600相同的功能,但减少了一点
https://stackoverflow.com/questions/8788817
复制相似问题