Repository navigation
Description
There seems to be a problem with RPostgres when retrieving results involving aggregating timestamp with time zone columns to date. The SQL that is generated (displayed with show_query()) yields a different result than what is actually retrieved by RPostgres. RPostgreSQL generates the same SQL, and retrieves the correct result.
In the following example, focus on the 2019-05-01 data, which should have a minimum of 24 and a maximum of 47.
library(tidyverse)
library(lubridate)
library(RPostgres)
conn <- dbConnect(Postgres(),
host = "dbhost",
user = "dbuser",
dbname = "dbname")
example <- tibble(val = seq(0:70)) %>%
mutate(ts = ymd_hms("2019-04-30 00:00:00", tz = "US/Alaska") + hours(val))
example %>%
mutate(dte = date(ts)) %>%
group_by(dte) %>%
summarize(min = min(val, na.rm = TRUE),
max = max(val, na.rm = TRUE))
That yields the correct result:
dte min max
<date> <int> <int>
1 2019-04-30 1 23
2 2019-05-01 24 47
3 2019-05-02 48 71
If we round-trip this through the database we get a different answer:
dbWriteTable(conn, "example", example,
overwrite = TRUE, append = FALSE)
conn %>%
tbl("example") %>%
mutate(dte = date(ts)) %>%
group_by(dte) %>%
summarize(min = min(val, na.rm = TRUE),
max = max(val, na.rm = TRUE))
Here's the result. The values for min and max appear to be off by 8 hours as though it's treating the timestamp of the data in the database as UTC (rather than US/Alaska).
dte min max
<date> <int> <int>
1 2019-04-30 1 15
2 2019-05-02 40 63
3 2019-05-03 64 71
4 2019-05-01 16 39
It's not the query that is generated, which gives the correct result when run inside Postgres. I get the same query when I load RPostgreSQL and use it's database driver, but it loads the proper results.
Here's the show_query() output:
<SQL>
SELECT "dte", MIN("val") AS "min", MAX("val") AS "max"
FROM (SELECT "val", "ts", date("ts") AS "dte"
FROM "example") "dbplyr_057"
GROUP BY "dte"
And the results of that query when run inside the database using psql:
dte | min | max
------------+-----+-----
2019-04-30 | 1 | 23
2019-05-01 | 24 | 47
2019-05-02 | 48 | 71
Activity
troels commentedon Nov 27, 2019
Hi @cswingle
This is likely due to RPostgres setting the default timezone of the connection to UTC.
If you create your connection by e.g.:
or even:
you might get the expected result.
cswingle commentedon Nov 27, 2019
@troels,
Thanks! Connecting with an explicit timezone, especially one that doesn't match your local timezone doesn't seem like a very sensible default.
Unfortunately, neither of your suggestions work, at least not with the latest version of RPostgres on CRAN (1.1.1):
The connection parameters available in libpq (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS) don't include
timezone, but you can pass options viaoptions, but I tried setting timezone this way (options = "-c timezone=US/Alaska") but the query still returns incorrect results. Usingtimezone = NULLalso returns a valid connection, but incorrect results.Perhaps the best solution would be to remove the code in RPostgres that sets the timezone to UTC? Any idea where that happens?
trafficonese commentedon Nov 27, 2019
I think the timezone argument is only on the dev-version. So you would have to install it with:
devtools::install_github("r-dbi/RPostgres")The UTC default is set here:
RPostgres/R/PqConnection.R
Line 163 in 6d0cc57
Set the default timezone to NULL on dbConnect
cswingle commentedon Nov 27, 2019
@trafficonese Thanks. I submitted a pull request to set the default for the
timezoneoption toNULL. My feeling is that it's the most logical and is the least surprising to use the timezone defined in the database when making a connection. That's the way every Postgres client I've used appears to work (psql, pgAdmin, Pythonpsycopg2, PHP, Golib/pq, etc.). Either that or they're all using the local timezone, which matches the database timezone in every database I've managed.cswingle commentedon Dec 14, 2019
I closed my pull request, which fixed this particular issue, but broke the correct retrieval of timestamp data. So I don't know how to fix this issue, except to do the
date()aggregation aftercollect(), which defeats some of the utility of r-dbi and letting the database do most of the heavy lifting before bringing the data locally.cswingle commentedon Dec 14, 2019
Another way to demonstrate the issue with the same
exampletable in the database is this:The
tscolumn appears correct, as it is in the database, starting with 1 AM, on April 30, 2019. But a little bit further down starting on row 16 you can see thatdate(ts)isn't right:date('2019-04-30 16:00:00') != '2019-05-01'. It's aggregating the timestamp as though it's UTC, but when retrieving the timestamp itself, it's getting it in US/Alaska.krlmlr commentedon Dec 17, 2019
Do we need a
timezone_outargument as in {odbc}'s implementation ofdbConnect()?krlmlr commentedon Dec 27, 2020
Is this a duplicate of #222 by any chance?
cswingley commentedon Dec 27, 2020
@krlmlr I'm not sure if it is or not. I tried using @iangow's
dbExecute(con, "SET timezone TO 'UTC'")from #222 and that didn't work. However, when I dodbExecute(conn, "SET timezone TO 'US/Alaska'")(my local time zone, which also matches thetimezonePostgres setting), I get the proper date aggregation. Which really doesn't make much sense to me, since the database is already configured with US/Alaska.I get the proper result:
krlmlr commentedon Jan 3, 2021
It is crucial that the
timezoneargument todbConnect()is set correctly. Don't executeSET TIMEZONE = ...after connecting,dbConnect()does that for you.With #276:
Created on 2021-01-03 by the reprex package (v0.3.0)
krlmlr commentedon Jan 3, 2021
The default setting of the
timezoneargument is"UTC". With #276 you can set it toNULLto use the server's time zone.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?
cswingley commentedon Jan 3, 2021
Looks good to me, thanks!
baderstine commentedon Jan 19, 2021
Should I expect to get really odd results when selecting from timestamp columns using RPostgres 1.2.0?
For example:
within pgAdmin 4.x the value is
2018-07-27 09:19:43(column type is "timestamp without time zone") but afterThe same value is returned as
2719-03-09 05:40:03within R (3.6.3).... and after updating to RPostgres v1.3.1 the value now returned as
2719-04-22 05:40:03Also get really strange results from my db when running your test-timezone.R, which really seems like a date formatting issue:
I ran
show datestyleand it returned "ISO, DMY".On a different PostgreSQL database that I connect to using RPostgres,
show datestylereturns "ISO, MDY" and queries of this database return perfectly normal results for all of the above queries (timestamps, etc. are correct).krlmlr commentedon Jan 20, 2021
@baderstine: Several 100 years off looks like a different problem, can you please open a new issue?
Off the top of my head, the datestyle may be relevant for the correct functioning of RPostgres. Maybe we should
SET DATESTYLEindbConnect()?baderstine commentedon Jan 20, 2021
Thanks. Opened #287
iangow commentedon Jan 20, 2021
@krlmlr
I played around with
SET DATESTYLEusing your example above and it didn't seem to make any difference. There's actually a sense in whichSET timezonedoesn't matter, as illustrated by the following examples. Inexample2, the "original" data is expressed in terms ofAEDT(Australia/Sydney) and are stored in both R and PostgreSQL in that way; thedatefunction is relative toAEDTno matter the value oftimezone.The good news: round-tripping the data (R -> PostgreSQL -> R) leads to no loss or errors.
The bad news: the
datefunction requires user attention to time zones.Created on 2021-01-20 by the reprex package (v0.3.0)
github-actions commentedon Jan 21, 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.