调整R中的数据时区

调整R中的数据时区,r,datetime,time,posixlt,R,Datetime,Time,Posixlt,由于某些原因,我无法通过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" 可以更改Sys.time()的时区 如何解决它?试试这个: time <- "Wed Jun 22 01:53:56 +0000 2016" strptime(time, fo

由于某些原因,我无法通过
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"
可以更改
Sys.time()的时区

如何解决它?

试试这个:

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"

time
strtime
返回一个
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>
或者使用
strtime
并将
t
转换为
POSIXct
,然后返回到
POSIXlt

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

t我认为在时间向量上运行前两个posixlt命令时,实际上是在更改向量的时区,而不是时间。所以它现在认为“t”是达尔文时间的21:53,而不是EST。试试
format(t,tz='Australia/Darwin',usetz=TRUE)
ct <- as.POSIXct(time, tz = "Australia/Darwin", format = "%a %b %d %H:%M:%S %z %Y")
t <- as.POSIXlt(ct)
t <- strptime(time, format = "%a %b %d %H:%M:%S %z %Y")
t <- as.POSIXlt(as.POSIXct(t, tz = "Australia/Darwin"))