2016-09-26 84 views
2

出于某种原因,我无法通过as.POSIXlt调整时区。调整R中的数据时区

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" 

的时区如何解决呢?

+0

我想在运行前两个posixlt命令在时间的矢量上,你实际上正在改变矢量的时区,但不是时间。所以现在认为't'在达尔文时间是21:53而不是EST。 –

+1

试试'format(t,tz ='Australia/Darwin',usetz = TRUE)' –

回答

0

试试这个:

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" 
0

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和转换tPOSIXct然后回到POSIXlt

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