3

我需要在动物园对象的索引上使用 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"
4

3 回答 3

5

假设我们有这个样本数据:

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"代替并注意R News 4/1"GMT"中有关日期和时间的文章。

于 2012-01-09T13:39:23.127 回答
4

您可以偏移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-09T13:41:33.267 回答
1

我建议使用 as.POSIXlt 转换为日期对象,包裹在 as.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 相同的效果,但略逊一筹

于 2020-04-02T15:55:12.023 回答