Repository navigation
Closed
Description
Using Rpostgres, my R session defaults to "America/Toronto" timezone, and the Postgres database I am working with is in UTC-04 by default. I'm finding that even if I change the session time zone in Postgres to "localtime" (which helps WHERE statements work correctly), dbGetQuery() still shifts the time down four hours when displaying it in R.
Does dbGetQuery() and company just always assume the Postgres database is 'UTC' no matter what the actual Postgres session time zone is set to?
I noticed a fix on another manifestation of dbConnect() in the odbc world here, so I wondered if it was a universal issue related to the generic method.
Here is an example:
library(Rpostgres)
con_pg <- dbConnect(RPostgres::Postgres())
#default R session time zone
Sys.timezone()
#> [1] "America/Toronto"
#some fake dates (one without and one with time zone)
dbExecute(con_pg, "DROP table IF EXISTS development.test")
#> [1] 0
dbExecute(
con_pg,
"CREATE TABLE development.test
(
ts_naked timestamp without time zone,
ts_tz timestamp with time zone
);"
)
#> [1] 0
dbExecute(con_pg,
"INSERT INTO
development.test (ts_naked, ts_tz)
VALUES
(TIMESTAMP '2016-08-12 10:00:00-04',
TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00-04')")
#> [1] 1
#So weird
dbGetQuery(con_pg, "select * from development.test WHERE ts_naked = ts_tz")
#> [1] ts_naked ts_tz
#> <0 rows> (or 0-length row.names)
#R seems to shift UP the time in Postgres
#even though data isn't being passed between the two systems
dbGetQuery(con_pg, "select * from development.test WHERE ts_naked = ts_tz - interval '4h'")
#> ts_naked ts_tz
#> 1 2016-08-12 10:00:00 2016-08-12 10:00:00
#set postgres session timezone to local time (as seen in earlier issues)
dbExecute(con_pg, "set timezone to 'localtime'")
#> [1] 0
dbGetQuery(con_pg, "show timezone")
#> TimeZone
#> 1 localtime
#The WHERE statement now works even though the ts_tz is displayed as four hours earlier by R
dbGetQuery(con_pg, "select * from development.test WHERE ts_naked = ts_tz")
#> ts_naked ts_tz
#> 1 2016-08-12 10:00:00 2016-08-12 06:00:00
#Setting the R session environment to UTC seems to fix it
Sys.setenv(TZ="UTC")
dbGetQuery(con_pg, "select * from development.test WHERE ts_naked = ts_tz")
#> ts_naked ts_tz
#> 1 2016-08-12 10:00:00 2016-08-12 10:00:00
dbGetQuery(con_pg, "select EXTRACT(TIMEZONE from ts_tz) from development.test")
#> date_part
#> 1 -14400
Reacted by Sebastian, Rima Bouchakri, Devin Mabra and Daniel Possenriede
Reacted by Louis Mullie
Activity
krlmlr commentedon Dec 17, 2019
Thanks. The
dbConnect()method has atimezoneargument where you can specify the timezone. Does it work for you? You need the development version 1.2.0, which will hit CRAN very soon.dkipb commentedon Dec 19, 2019
Thanks for this!
It seems to work on the Postgres side, but not when we pull the values into R. I think the function is assuming that the data we are pulling in is in "UTC".
hadley commentedon Apr 25, 2020
Slightly cleaner reprex:
Created on 2020-04-26 by the reprex package (v0.3.0)
But it's not clear to me if this behaviour is incorrect because I don't understand what a timestamp without a time zone means.
dkipb commentedon Apr 25, 2020
Hi Hadley,
I've re-written it just a bit to show what I mean. I think dbGetQuery shifts the date with timezone down four hours here because it is assuming it's coming from UTC.
hadley commentedon Apr 25, 2020
@dkipb but that doesn't show that the time is shifted, it just shows it's printed representation is shifted (which it will be if the timezone is set to a different value)
dkipb commentedon Apr 25, 2020
@hadley That makes sense, however when you assign this to a data.frame, your ts_tz column becomes 6pm EDT.
Setting the WHERE statement aside...
For some reason, in a pg session set to "America/Toronto" - when 10pm-04 is pulled into R, dbGetQuery seems to only see the 10pm, assume it's UTC, and prints out 6pm.
When you switch the pg session to "UTC" - 10pm-04 becomes 14pm-00. When this is pulled into R, dbGetQuery seems to only see the 14pm, assumes it's UTC, and prints out 10pm. It just happened to be indirectly correct in this case.
In the system itself, for sure, the time hasn't shifted. But the time-shifted printing in R can wreck havoc for further data processing.
hadley commentedon Apr 25, 2020
@dkipb right, it's not that I don't believe you, just that your reprex doesn't really illustrate the underlying problem. I'd recommend printing the results in such a way that you can actually see the timezones of the output — this is a complex problem and you need to make the reprex crystal clear. (It would also help if you used
```Rto get syntax highlighting in your reprexes).dkipb commentedon Apr 25, 2020
@hadley For sure, I will. I'm new to this and appreciate you giving input on how to better describe the issue. Here is the problem pared down without the WHERE statement complicating it.
krlmlr commentedon Apr 26, 2020
Thanks, it looks like we need to take better care of time zone offsets, and the
timezoneargument doesn't work right yet.I've augmented the reprex with a call into the
psqlutility to show what's actually stored in the database, and with two more rows containing UTC times.Created on 2020-04-26 by the reprex package (v0.3.0)
dkipb commentedon Apr 27, 2020
Thanks @krlmlr and @hadley! Very much appreciated.
Is there anything else I can do to help clarify the issue? (I'm not sure about next steps this is the first time I've tried opening an issue on Github).
hadley commentedon Apr 27, 2020
I think we understand the problem now, which is obviously the most important first step. The next challenge is implementing a fix — this depends on @krlmlr's timetable (and it doesn't look like RPostgres otherwise needs work).
dpprdan commentedon Apr 29, 2020
I ran into this issue yesterday and can hopefully add some more informative (but possibly redundant) bits and pieces.
I think the underlying problem is that RPostgres adds the
Sys.timezone()offset to what PostgreSQL returns. PostgreSQL saves all timestamps in UTC, but returns them in the timezone specified for the connection.From https://www.postgresql.org/docs/12/datatype-datetime.html, emphasis mine.
So in R we get the UTC time + the offset for the timezone of the connection (from PostgreSQL) + the offset from
Sys.timezone()from RPostgres. IMO we want the former offset, but not the latter.To illustrate, I am choosing a different time zone for the connection (“Europe/Riga”, currently EEST, i.e. UTC +3) from my
Sys.timezone()(“Europe/Berlin”, CEST/UTC +2).The above is
2020-04-27 22:00:01in UTC plus 3 added by Postgres plus 2 added by RPostgres.The above is
2020-04-28 00:00:01in UTC plus 3 added by Postgres plus 2 added by RPostgres.So the above is stored as
2020-04-27 21:00:01in UTC. On output there are 3 hours added back again by Postgres plus 2 added by RPostgres.Apparently the following two “data types” do not experience this problem:
NOW()OTOH returns atimestamp with time zone, so also shows the problematic behaviour, i.e. adds the, in this case two hour, offset ofSys.timezone():Something I have not yet wrapped my head around is the behaviour of
timestamp without time zonein areprex():Usually, for a
timestamp without time zoneno conversions are made and it is returned ‘as-is’ by PostgreSQL.Same source, emphasis mine.
Locally, i.e. in RStudio and RGUI I indeed get
2020-04-28 00:00:01, but in areprex()the result is off by +1 hour, regardless of time zone(s) specified.This also affects a possible workaround for the general
RPostgresissue. If one explicitly casts atimestamp with time zoneto the desired output time zone, PostgreSQL apparently returns atimestamp without time zone(which I don’t fully understand because one explicitly casts it to a time zone, but 🤷♂️). Again, viareprex()the result is off by +1 hour, so this obviously is not a very reliable workaround.Current time in Europe/Riga:
And just to confirm: with the UTC +3 timezone, RPostgres adds 3 hours to what PostgreSQL returns.
Created on 2020-04-29 by the reprex package (v0.3.0)
Session info
dpprdan commentedon May 4, 2020
The 1 hour offset in the
reprex()that I reported above, was apparently caused by me runningSys.setenv(TZ='Europe/Riga')in my main session, which gets carried through toreprex::reprex(). My native timezone is "Europe/Berlin". "Europe/Riga" is +1 relative to "Europe/Berlin". SincedbGetQuery(con, "SELECT timezone('Europe/Riga', NOW());")returns atimestamp without timezone, this 1 hour offset is added to the result, as reported in #190.iangow commentedon Jun 6, 2020
Sorry, I got here from #245 and it seems a bit late.
I think the TL;DR for now is: Always
SET timezone TO 'UTC'before readingtimestamp with time zonedata into R usingRPostgres.(The example below shows that
timezoneneed not be set toUTCwhen making the connection.)Created on 2020-06-06 by the reprex package (v0.3.0)
dkipb commentedon Jun 6, 2020
Ian, that’s a really good point. Where we ran into trouble is that the system we are querying from has a mix of time zone and non time zone variables (I know, I know). So once you shift, you can’t do comparisons anymore between those dates. And, we use dbGetQuery a lot so it would be a lot of time zone shifting back and forth as the code runs. Lots of gymnastics no matter how you navigate it.
krlmlr commentedon Dec 27, 2020
I'll set up a server configured with a non-UTC time zone for testing.
krlmlr commentedon Jan 3, 2021
Do not fiddle with the timezone setting after establishing the connection.
#276 now has
timezoneandtimezone_outarguments with correct translation.With #276 and a slightly different reprex I see:
Created on 2021-01-03 by the reprex package (v0.3.0)
Merge pull request #276 from r-dbi/b-timezone
krlmlr commentedon Jan 3, 2021
Should be fixed now. Could you please test the development version in the next few days, and let me know if any problems still arise?
dkipb commentedon Jan 6, 2021
The test works great using our RPostgres connection. Our team will test this in a situation where we had to use a workaround a bit later and will let you know if anything comes up.
Thank you, it is very nice to start 2021 with this fix! Very much appreciated.
github-actions commentedon Jan 7, 2022
This old thread has been automatically locked. If you think you have found something related to this, please open a new issue and link to this old issue if necessary.