2016-09-26 85 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"))