user3022875
user3022875

Reputation: 9018

Convert to GMT time without changing date

I query a data base and get back a vector of dates in EST time

d =as.POSIXct(c("2015-06-19 00:38:08 EST","2015-06-19 00:38:33 EST"))
d

Here the vector

d
[1] "2015-06-19 00:38:08 EST" "2015-06-19 00:38:33 EST"

BUT I want the timezone to be in GMT time.

How can I get results that look like

d
[1] "2015-06-19 00:38:08 GMT" "2015-06-19 00:38:33 GMT"

Upvotes: 1

Views: 920

Answers (2)

IRTFM
IRTFM

Reputation: 263332

First, we need to have an unambiguous way of making a time in US New York time (for which EST" is also ambiguous owing to the existence of an Eastern time zone in Australia as well. Better would be EST5EDT or "America/New_York".) If you run the code you used in a different time zone you don't get the same time:

> d =as.POSIXct(c("2015-06-19 00:38:08 EST","2015-06-19 00:38:33 EST"))
> d
[1] "2015-06-19 00:38:08 PDT" "2015-06-19 00:38:33 PDT"

The time zone portion of character times is basically ignored at the time of creation by as.POSIXct. Instead use:

> d =as.POSIXct(c("2015-06-19 00:38:08 EST","2015-06-19 00:38:33 EST"), tz="America/New_York", usetz=TRUE)
> d
[1] "2015-06-19 00:38:08 EDT" "2015-06-19 00:38:33 EDT"

Notice that the correct display of the Daylight Savings time has been displayed. Then you can use format.POSIXt for output of "the same time" in the GMT/UCT/UTC timezone:

> format(d, tz="GMT")
[1] "2015-06-19 04:38:08" "2015-06-19 04:38:33"

I hope this is a fair summary of how strptime handles datetime input:

Date-times are implicitly entered in the current timezone set by locale setting with any trailing tz indicator ignored with no warning and stored as UCT with an offset determined by the locale's difference from UCT. The timezone formatting %-'specials' are only used on output with strftime and format.POSIXt.

Upvotes: 1

jlhoward
jlhoward

Reputation: 59345

Like this? I'm not exactly sure what your trying to accomplish. The title of your question asks to "change the time w/o changing the date" but your example changes nothing but the timezone. This produces the result in your example.

d <- as.POSIXct(c("2015-06-19 00:38:08 EST","2015-06-19 00:38:33 EST"))
d
# [1] "2015-06-19 00:38:08 EDT" "2015-06-19 00:38:33 EDT"
as.POSIXct(as.character(d),tz="GMT")
# [1] "2015-06-19 00:38:08 GMT" "2015-06-19 00:38:33 GMT"

Upvotes: 3

Related Questions