2

For some reason I can't adjust the time zone by 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"

Can't change the time zone

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

Can change the time zone for 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"

How to solve it?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Yan Chen
  • 31
  • 2
  • I think when running the first two posixlt commands on the vector of time you are actually changing the timezone of the vector but not the time. So it now thinks that 't' is 21:53 in Darwin time instead of EST. – Daniel Winkler Sep 26 '16 at 07:03
  • 1
    Try `format(t, tz='Australia/Darwin', usetz=TRUE) ` – Daniel Winkler Sep 26 '16 at 07:12

2 Answers2

0

Try this:

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"
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
0

strptime returns a POSIXlt object. Calling as.POSIXlt on t just returns t. There is no as.POSIXlt.POSIXlt method, so as.POSIXlt.default is dispatched. And you can see the first if statement checks if x inherits the POSIXlt class, and returns x if that's true.

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>

You either need to use as.POSIXct instead of strptime and specify the timezone you want, then convert to POSIXlt:

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

Or use strptime and convert t to POSIXct and then back to POSIXlt:

t <- strptime(time, format = "%a %b %d %H:%M:%S %z %Y")
t <- as.POSIXlt(as.POSIXct(t, tz = "Australia/Darwin"))
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418