【问题标题】:Adjust data time zone in R在 R 中调整数据时区
【发布时间】:2017-02-03 10:02:40
【问题描述】:

由于某种原因,我无法通过as.POSIXlt 调整时区。

time <- "Wed Jun 22 01:53:56 +0000 2016"
t <- strptime(time, format = '%a %b %d %H:%M:%S %z %Y')
t
[1] "2016-06-21 21:53:56"

无法更改时区

as.POSIXlt(t, "EST")
[1] "2016-06-21 21:53:56"
as.POSIXlt(t, "Australia/Darwin")
[1] "2016-06-21 21:53:56"

可以更改Sys.time()的时区

as.POSIXlt(Sys.time(), "EST")
[1] "2016-09-26 01:47:22 EST"
as.POSIXlt(Sys.time(), "Australia/Darwin")
[1] "2016-09-26 16:19:48 ACST"

如何解决?

【问题讨论】:

  • 我认为在时间向量上运行前两个 posixlt 命令时,您实际上是在更改向量的时区,而不是时间。所以它现在认为 't' 是达尔文时间的 21:53 而不是 EST。
  • 试试format(t, tz='Australia/Darwin', usetz=TRUE)

标签: r datetime time posixlt


【解决方案1】:

strptime 返回一个POSIXlt 对象。在t 上调用as.POSIXlt 只会返回t。没有as.POSIXlt.POSIXlt 方法,所以as.POSIXlt.default 被调度。你可以看到第一个if 语句检查x 是否继承POSIXlt 类,如果是则返回x

str(t)
# POSIXlt[1:1], format: "2016-06-21 20:53:56"
print(as.POSIXlt.default)
# function (x, tz = "", ...) 
# {
#     if (inherits(x, "POSIXlt")) 
#         return(x)
#     if (is.logical(x) && all(is.na(x))) 
#         return(as.POSIXlt(as.POSIXct.default(x), tz = tz))
#     stop(gettextf("do not know how to convert '%s' to class %s", 
#         deparse(substitute(x)), dQuote("POSIXlt")), domain = NA)
# }
# <bytecode: 0x2d6aa18>
# <environment: namespace:base>

您要么需要使用as.POSIXct 而不是strptime 并指定所需的时区,然后转换为POSIXlt

ct <- as.POSIXct(time, tz = "Australia/Darwin", format = "%a %b %d %H:%M:%S %z %Y")
t <- as.POSIXlt(ct)

或使用strptime 并将t 转换为POSIXct,然后再转换回POSIXlt

t <- strptime(time, format = "%a %b %d %H:%M:%S %z %Y")
t <- as.POSIXlt(as.POSIXct(t, tz = "Australia/Darwin"))

【讨论】:

    【解决方案2】:

    试试这个:

    time <- "Wed Jun 22 01:53:56 +0000 2016"
    strptime(time, format = '%a %b %d %H:%M:%S %z %Y')
    #[1] "2016-06-22 07:23:56"
    strptime(time, format = '%a %b %d %H:%M:%S %z %Y', tz="EST")
    #[1] "2016-06-21 20:53:56"
    strptime(time, format = '%a %b %d %H:%M:%S %z %Y', tz="Australia/Darwin")
    #[1] "2016-06-22 11:23:56"
    

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 2019-12-26
      • 2014-04-09
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多