Skip to content

Incorrect results when aggregating timestamp to date #229

Closed

Description

@cswingle

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

  1. troels commented on Nov 27, 2019

    @troels
    Contributor

    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.:

    conn <- dbConnect(Postgres(),
                      host = "dbhost",
                      user = "dbuser",
                      dbname = "dbname",
                      timezone='US/Alaska'
    )
    

    or even:

    conn <- dbConnect(Postgres(),
                      host = "dbhost",
                      user = "dbuser",
                      dbname = "dbname",
                      timezone=NULL
    )
    

    you might get the expected result.

  2. cswingle commented on Nov 27, 2019

    @cswingle
    Author

    @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):

    library(tidyverse)
    library(RPostgres)
    
    conn <- dbConnect(Postgres(),
                      host = "dbhost",
                      user = "dbuser",
                      dbname = "dbname",
                      timezone = "US/Alaska")
    
    Error in connection_create(names(opts), as.vector(opts)) :
      invalid connection option "timezone"

    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 via options, but I tried setting timezone this way (options = "-c timezone=US/Alaska") but the query still returns incorrect results. Using timezone = NULL also 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?

  3. trafficonese commented on Nov 27, 2019

    @trafficonese

    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:

    check_interrupts = FALSE, timezone = "UTC") {

  4. added a commit that references this issue on Nov 27, 2019
    2d36ecf
  5. cswingle commented on Nov 27, 2019

    @cswingle
    Author

    @trafficonese Thanks. I submitted a pull request to set the default for the timezone option to NULL. 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, Python psycopg2, PHP, Go lib/pq, etc.). Either that or they're all using the local timezone, which matches the database timezone in every database I've managed.

  6. cswingle commented on Dec 14, 2019

    @cswingle
    Author

    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 after collect(), which defeats some of the utility of r-dbi and letting the database do most of the heavy lifting before bringing the data locally.

  7. cswingle commented on Dec 14, 2019

    @cswingle
    Author

    Another way to demonstrate the issue with the same example table in the database is this:

    > dbGetQuery(conn, "SELECT ts, date(ts) FROM example")
    
                        ts       date
    1  2019-04-30 01:00:00 2019-04-30
    2  2019-04-30 02:00:00 2019-04-30
    ...
    15 2019-04-30 15:00:00 2019-04-30
    16 2019-04-30 16:00:00 2019-05-01
    17 2019-04-30 17:00:00 2019-05-01
    ...

    The ts column 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 that date(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.

  8. krlmlr commented on Dec 17, 2019

    @krlmlr
    Member

    Do we need a timezone_out argument as in {odbc}'s implementation of dbConnect() ?

  9. added this to the 1.2.2 milestone on Dec 26, 2020
  10. krlmlr commented on Dec 27, 2020

    @krlmlr
    Member

    Is this a duplicate of #222 by any chance?

  11. cswingley commented on Dec 27, 2020

    @cswingley

    @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 do dbExecute(conn, "SET timezone TO 'US/Alaska'") (my local time zone, which also matches the timezone Postgres 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.

    dbExecute(conn, "SET timezone TO 'US/Alaska'")
    
    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)
      )

    I get the proper result:

      # A tibble: 3 x 3
        dte          min   max 
        <date>     <int> <int>
    1 2019-04-30     1    23
    2 2019-05-01    24    47
    3 2019-05-02    48    71
  12. modified the milestones: 1.2.2, 1.2.3 on Jan 2, 2021
  13. krlmlr commented on Jan 3, 2021

    @krlmlr
    Member

    It is crucial that the timezone argument to dbConnect() is set correctly. Don't execute SET TIMEZONE = ... after connecting, dbConnect() does that for you.

    With #276:

    library(tidyverse)
    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #> 
    #>     date, intersect, setdiff, union
    library(RPostgres)
    
    my_tz <- "US/Alaska"
    
    example <-
      tibble(val = seq(0:70)) %>%
      mutate(ts = ymd_hms("2019-04-30 00:00:00", tz = my_tz) + hours(val))
    
    example
    #> # A tibble: 71 x 2
    #>      val ts                 
    #>    <int> <dttm>             
    #>  1     1 2019-04-30 01:00:00
    #>  2     2 2019-04-30 02:00:00
    #>  3     3 2019-04-30 03:00:00
    #>  4     4 2019-04-30 04:00:00
    #>  5     5 2019-04-30 05:00:00
    #>  6     6 2019-04-30 06:00:00
    #>  7     7 2019-04-30 07:00:00
    #>  8     8 2019-04-30 08:00:00
    #>  9     9 2019-04-30 09:00:00
    #> 10    10 2019-04-30 10:00:00
    #> # … with 61 more rows
    
    example %>%
      mutate(dte = date(ts)) %>%
      group_by(dte) %>%
      summarize(
        min = min(val, na.rm = TRUE),
        max = max(val, na.rm = TRUE)
      )
    #> `summarise()` has ungrouped output. You can override using the `.groups` argument.
    #> # A tibble: 3 x 3
    #>   dte          min   max
    #> * <date>     <int> <int>
    #> 1 2019-04-30     1    23
    #> 2 2019-05-01    24    47
    #> 3 2019-05-02    48    71
    
    my_tz <- "US/Alaska"
    
    conn <- dbConnect(Postgres(), timezone = my_tz)
    
    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)
      ) %>%
      arrange(dte)
    #> # Source:     lazy query [?? x 3]
    #> # Database:   postgres [kirill@/var/run/postgresql:5432/kirill]
    #> # Ordered by: dte
    #>   dte          min   max
    #>   <date>     <int> <int>
    #> 1 2019-04-30     1    23
    #> 2 2019-05-01    24    47
    #> 3 2019-05-02    48    71

    Created on 2021-01-03 by the reprex package (v0.3.0)

  14. krlmlr commented on Jan 3, 2021

    @krlmlr
    Member

    The default setting of the timezone argument is "UTC". With #276 you can set it to NULL to use the server's time zone.

  15. added a commit that references this issue on Jan 3, 2021
  16. krlmlr commented on Jan 3, 2021

    @krlmlr
    Member

    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?

  17. cswingley commented on Jan 3, 2021

    @cswingley

    Looks good to me, thanks!

  18. baderstine commented on Jan 19, 2021

    @baderstine
    Contributor

    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 after

    con  = RPostgres::dbConnect(RPostgres::Postgres(), 
                                host ..., 
                                port ..., 
                                dbname ..., 
                                user ..., 
                                password ..., 
                                sslmode = 'require', 
                                timezone = NULL)
    
    dbGetQuery(con, "select tzcolumn from tablename limit 1")
    

    The same value is returned as 2719-03-09 05:40:03 within R (3.6.3).

    ... and after updating to RPostgres v1.3.1 the value now returned as 2719-04-22 05:40:03

    Also get really strange results from my db when running your test-timezone.R, which really seems like a date formatting issue:

    >   query <- "SELECT '2018-01-01 12:30:00'::TIMESTAMP AS a, '2018-01-01 12:30:00'::TIMESTAMPTZ AS b"
    >   DBI::dbGetQuery(con, query)
                        a                   b
    1 0120-12-21 06:10:00 0120-12-21 00:37:49
    

    I ran show datestyle and it returned "ISO, DMY".
    On a different PostgreSQL database that I connect to using RPostgres, show datestyle returns "ISO, MDY" and queries of this database return perfectly normal results for all of the above queries (timestamps, etc. are correct).

  19. krlmlr commented on Jan 20, 2021

    @krlmlr
    Member

    @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 DATESTYLE in dbConnect()?

  20. baderstine commented on Jan 20, 2021

    @baderstine
    Contributor

    Thanks. Opened #287

  21. iangow commented on Jan 20, 2021

    @iangow

    @krlmlr

    I played around with SET DATESTYLE using your example above and it didn't seem to make any difference. There's actually a sense in which SET timezone doesn't matter, as illustrated by the following examples. In example2, the "original" data is expressed in terms of AEDT (Australia/Sydney) and are stored in both R and PostgreSQL in that way; the date function is relative to AEDT no matter the value of timezone.

    The good news: round-tripping the data (R -> PostgreSQL -> R) leads to no loss or errors.
    The bad news: the date function requires user attention to time zones.

    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #> 
    #>     date, intersect, setdiff, union
    library(dplyr, warn.conflicts = FALSE)
    library(DBI)
    
    ts1 <- ymd_hms("2012-03-26 03:12:13", tz = "Australia/Sydney")
    ts2 <- ymd_hms("2012-03-25 08:12:13", tz = "US/Alaska")
    date(ts1)
    #> [1] "2012-03-26"
    date(ts2)
    #> [1] "2012-03-25"
    
    # It seems that lubridate (or something) converts the datetimes to the
    # timezone of the first entry
    conn <- dbConnect(RPostgres::Postgres(), timezone = "US/Alaska")
    
    dbGetQuery(conn, "SHOW timezone;")
    #>    TimeZone
    #> 1 US/Alaska
    
    example2 <- tibble(ts = c(ts1, ts2))
    example2$ts[1]
    #> [1] "2012-03-26 03:12:13 AEDT"
    example2$ts[2]
    #> [1] "2012-03-26 03:12:13 AEDT"
    example2 %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-26 03:12:13 2012-03-26
    #> 2 2012-03-26 03:12:13 2012-03-26
    
    dbWriteTable(conn, "example2", example2,
                 overwrite = TRUE, append = FALSE, 
                 temporary = FALSE)
    
    example2_pg <- tbl(conn, "example2") 
    
    example2 %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-26 03:12:13 2012-03-26
    #> 2 2012-03-26 03:12:13 2012-03-26
    
    example2 %>% 
      collect() %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-26 03:12:13 2012-03-26
    #> 2 2012-03-26 03:12:13 2012-03-26
    
    example2 %>% 
      pull() %>%
      .[1]
    #> [1] "2012-03-26 03:12:13 AEDT"
    
    example2 %>% 
      pull() %>%
      .[2]
    #> [1] "2012-03-26 03:12:13 AEDT"
    
    dbDisconnect(conn)
    
    # Flip the order of the entries
    conn <- dbConnect(RPostgres::Postgres(), timezone = "US/Alaska")
    
    example3 <- tibble(ts = c(ts2, ts1))
    example3$ts[1]
    #> [1] "2012-03-25 08:12:13 AKDT"
    example3$ts[2]
    #> [1] "2012-03-25 08:12:13 AKDT"
    example3 %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-25 08:12:13 2012-03-25
    #> 2 2012-03-25 08:12:13 2012-03-25
    
    dbWriteTable(conn, "example3", example3,
                 overwrite = TRUE, append = FALSE)
    
    example3_pg <- tbl(conn, "example3") 
    
    example3 %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-25 08:12:13 2012-03-25
    #> 2 2012-03-25 08:12:13 2012-03-25
    
    example3 %>% 
      collect() %>%
      mutate(date = date(ts))
    #> # A tibble: 2 x 2
    #>   ts                  date      
    #>   <dttm>              <date>    
    #> 1 2012-03-25 08:12:13 2012-03-25
    #> 2 2012-03-25 08:12:13 2012-03-25
    
    
    example3 %>% 
      pull() %>%
      .[1]
    #> [1] "2012-03-25 08:12:13 AKDT"
    
    example3 %>% 
      pull() %>%
      .[2]
    #> [1] "2012-03-25 08:12:13 AKDT"

    Created on 2021-01-20 by the reprex package (v0.3.0)

  22. github-actions commented on Jan 21, 2022

    @github-actions
    Contributor

    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.

  23. locked and limited conversation to collaborators on Jan 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions