R 使用 as.Date() 转换带有 BST/GMT 标签的 POSIXct 日期

SWi*_*ams 3 r date posixct binary-search-tree xts

我需要在动物园对象的索引上使用 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"
Run Code Online (Sandbox Code Playgroud)

最小可重复的示例(不需要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"
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 5

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

library(zoo)
x <- as.POSIXct("2000-01-01", tz = "GMT")
Run Code Online (Sandbox Code Playgroud)

然后看看这些是否是你想要的:

# 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)
Run Code Online (Sandbox Code Playgroud)

还尝试"BST"替换"GMT"并注意R News 4/1 中有关日期和时间的文章。