Reputation: 9018
I have a POSIXct variable that reads 2016-12-15 20:11:29 PST but the PST is incorrect. It should actually read 2016-12-15 20:11:29 GMT
I need to make the time zone correct, GMT, then I need to convert it to New York time
So I am given 2016-12-15 20:11:29 PST. It really should be 2016-12-15 20:11:29 GMT then I need to convert 2016-12-15 20:11:29 GMT to "America/New_York" so the final result will be 16:11:29 America/New_York because new york time is BEHIND GMT time.
I've tried this many ways but can't get it to work. Any ideas?
p = as.POSIXct("2016-12-15 20:11:29 PST")
p
********** UPDATE ********* my real code uses a variable and the suggested solutions do not work. see below
p = as.POSIXct("2016-12-15 20:11:29 PST")
out = as.POSIXct(p, tz="GMT")
out
attr(out,"tzone") <- "America/New_York"
out
> out
[1] "2016-12-15 20:11:29 PST"
> attr(out,"tzone") <- "America/New_York"
> out
[1] "2016-12-15 23:11:29 EST" ### this is incorrect
*** This also doe snot work
p = as.POSIXct(p, usetz=TRUE, tz="GMT")
(format(p, tz="America/New_York") )
[1] "2016-12-15 23:11:29 EST"
> p = as.POSIXct(p, usetz=TRUE, tz="GMT")
> (format(p, tz="America/New_York") )
[1] "2016-12-15 23:11:29"
Upvotes: 2
Views: 1028
Reputation: 263301
I can get you most of the way there but R thinks your are wrong about the time differential:
> p = as.POSIXct("2016-12-15 20:11:29 PST", usetz=TRUE, tz="GMT")
> p
[1] "2016-12-15 20:11:29 GMT"
> (format(p, tz="America/New_York") )
[1] "2016-12-15 15:11:29"
Response to edit. I'm not seeing the problem. The numeric representation of time in R is always GMT. You can do things at input with parameter to blank out the wrong tz but then your output with format
or strftime
will simply need to specify a parameter for a different timezone. ( using a variable should have no effect.)
p = "2016-12-15 20:11:29 PST"
pp = as.POSIXct(p, usetz=TRUE, tz="GMT")
pp
[1] "2016-12-15 20:11:29 GMT"
Upvotes: 2
Reputation: 93803
Your issue is that your p
is in your system timezone by default:
p = as.POSIXct("2016-12-15 20:11:29 PST")
p
# I'm in Australian Eastern Standard Time, AEST
#[1] "2016-12-15 20:11:29 AEST"
as.numeric(p)
#[1] 1481796689
Convert this local datetime to UTC
, which changes the underlying data, by formatting and resetting the timezone to GMT (unless you are already in GMT, then it will do nothing of course):
p2 <- as.POSIXct(format(p),tz="UTC")
p2
#[1] "2016-12-15 20:11:29 UTC"
as.numeric(p2)
#[1] 1481832689
p2 - p
#Time difference of 10 hours
# ...which is the difference between AEST and GMT
Then you can adjust the timezone attribute, which will just alter the display of the date/time object. It does not affect the underlying numeric data:
attr(p2,"tzone") <- "America/New_York"
p2
#[1] "2016-12-15 15:11:29 EST"
as.numeric(p2)
#[1] 1481832689
Upvotes: 1