【问题标题】:R converting POSIXct dates with BST/GMT tags using as.Date()R 使用 as.Date() 转换带有 BST/GMT 标签的 POSIXct 日期
【发布时间】:2012-02-06 00:16:15
【问题描述】:

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

【问题讨论】:

  • 如果您提供可重现的示例,则更容易回答。猜测一下,在转换为 Date 之前转换为 character 是否有效?

标签: r date xts binary-search-tree posixct


【解决方案1】:

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

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 中有关日期和时间的文章。

【讨论】:

  • 请注意,问题归结为as.POSIXct""tz 的默认值表示当前时区,而as.Date.POSIXcttz 的默认值为"UTC" .
【解决方案2】:

您可以偏移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"

【讨论】:

  • 谢谢,这个答案正是我想要的,但不幸的是,对我来说,我正在使用的程序似乎不喜欢这样。无论如何,好帖子,我接受了 - 再次感谢。
  • @SWilliams “以后不喜欢它”是什么意思? d+3600 创建一个临时的,因此不应该影响您程序的任何其他部分。
【解决方案3】:

我建议使用 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 相同的效果,但略逊一筹

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2013-02-21
    • 2015-01-08
    • 2018-04-30
    • 2014-02-18
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多