Skip to content

dbGetQuery assuming postgres database is in UTC?  #222

Closed

Description

@dkipb

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

Activity

  1. krlmlr commented on Dec 17, 2019

    @krlmlr
    Member

    Thanks. The dbConnect() method has a timezone argument 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.

  2. dkipb commented on Dec 19, 2019

    @dkipb
    Author

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

    library(RPostgres)
    
    con_pg <- dbConnect(RPostgres::Postgres(), timezone="America/Toronto")
    
    Sys.timezone()
    #> [1] "America/Toronto"
    
    dbGetQuery(con_pg, "show timezone")
    #>          TimeZone
    #> 1 America/Toronto
    
    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',
      TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00')")
    #> [1] 1
    
    #The time shifts down 4 hours. 
    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
    
    
    #So, if I set the system timezone to UTC it works... 
    
    
    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
  3. hadley commented on Apr 25, 2020

    @hadley
    Member

    Slightly cleaner reprex:

    library(DBI)
    
    Sys.setenv(TZ = "Pacific/Auckland")
    Sys.timezone()
    #> [1] "Pacific/Auckland"
    
    con <- dbConnect(RPostgres::Postgres())
    dbExecute(con, "SET TIME ZONE 'America/Toronto'")
    #> [1] 0
    dbGetQuery(con, "SHOW TIME ZONE")
    #>          TimeZone
    #> 1 America/Toronto
    
    dbExecute(con, "
      CREATE TEMPORARY TABLE tz_test(
        ts_naked TIMESTAMP,
        ts_tz TIMESTAMP WITH TIME ZONE
      )
    ")
    #> [1] 0
    dbExecute(con, "
      INSERT INTO tz_test (ts_naked, ts_tz)
      VALUES 
      (
        TIMESTAMP '2016-08-12 10:00:00', 
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00'
      ),
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00',
        TIMESTAMP '2016-08-12 10:00:00'
      )
    ")
    #> [1] 2
    
    dbGetQuery(con, "SELECT * FROM tz_test")
    #>              ts_naked               ts_tz
    #> 1 2016-08-12 10:00:00 2016-08-12 22:00:00
    #> 2 2016-08-12 10:00:00 2016-08-12 22:00:00

    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.

  4. dkipb commented on Apr 25, 2020

    @dkipb
    Author

    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.

    library(DBI)
    library(tidyverse)
    
    Sys.setenv(TZ="America/Toronto")
    Sys.timezone()
    #> [1] "America/Toronto"
    
    dbExecute(con, "SET TIME ZONE 'America/Toronto'")
    #> [1] 0
    
    dbGetQuery(con, "SHOW TIME ZONE")
    #>          TimeZone
    #> 1 America/Toronto
    
    dbExecute(con, "
      CREATE TEMPORARY TABLE tz_test(
        ts_naked TIMESTAMP,
        ts_tz TIMESTAMP WITH TIME ZONE
      )
    ")
    #> [1] 0
    
    dbExecute(con, "
      INSERT INTO tz_test (ts_naked, ts_tz)
      VALUES 
      (
        TIMESTAMP '2016-08-12 10:00:00', 
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00'
      ),
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00',
        TIMESTAMP '2016-08-12 10:00:00'
      )
    ")
    #> [1] 2
    
    dbGetQuery(con, "SELECT * FROM tz_test")
    #>              ts_naked               ts_tz
    #> 1 2016-08-12 10:00:00 2016-08-12 06:00:00
    #> 2 2016-08-12 10:00:00 2016-08-12 06:00:00
    
    dbGetQuery(con, "SELECT * FROM tz_test WHERE ts_naked=ts_tz ")
    #>              ts_naked               ts_tz
    #> 1 2016-08-12 10:00:00 2016-08-12 06:00:00
    #> 2 2016-08-12 10:00:00 2016-08-12 06:00:00
    
    dbExecute(con, "SET TIME ZONE 'UTC'")
    #> [1] 0
    
    dbGetQuery(con, "SELECT * FROM tz_test WHERE ts_naked=ts_tz AT TIME ZONE 'America/Toronto'")
    #>              ts_naked               ts_tz
    #> 1 2016-08-12 10:00:00 2016-08-12 10:00:00
    #> 2 2016-08-12 10:00:00 2016-08-12 10:00:00
  5. hadley commented on Apr 25, 2020

    @hadley
    Member

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

  6. dkipb commented on Apr 25, 2020

    @dkipb
    Author

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

  7. hadley commented on Apr 25, 2020

    @hadley
    Member

    @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 ```R to get syntax highlighting in your reprexes).

  8. dkipb commented on Apr 25, 2020

    @dkipb
    Author

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

    library(Rpostgres)
    library(tidyverse) 
    
    con <- dbConnect(RPostgres::Postgres())
    
    Sys.setenv(TZ="America/Toronto")
    Sys.timezone()
    #> [1] "America/Toronto"
    
    dbGetQuery(con, "SHOW TIME ZONE")
    #>          TimeZone
    #> 1 America/Toronto
    
    dbExecute(con, "
      CREATE TEMPORARY TABLE tz_test(
        ts_naked TIMESTAMP,
        ts_tz TIMESTAMP WITH TIME ZONE
      )
    ")
    #> [1] 0
    
    dbExecute(con, "
      INSERT INTO tz_test (ts_naked, ts_tz)
      VALUES 
      (
        TIMESTAMP '2016-08-12 10:00:00', 
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00'
      ),
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00',
        TIMESTAMP '2016-08-12 10:00:00'
      )
    ")
    #> [1] 2
    
    r_df <- dbGetQuery(con, "SELECT * FROM tz_test")
    
    r_df$ts_naked
    #> [1] "2016-08-12 10:00:00 EDT" "2016-08-12 10:00:00 EDT"
    
    r_df$ts_tz
    #> [1] "2016-08-12 06:00:00 EDT" "2016-08-12 06:00:00 EDT"
  9. krlmlr commented on Apr 26, 2020

    @krlmlr
    Member

    Thanks, it looks like we need to take better care of time zone offsets, and the timezone argument doesn't work right yet.

    I've augmented the reprex with a call into the psql utility to show what's actually stored in the database, and with two more rows containing UTC times.

    library(RPostgres)
    library(tidyverse)
    
    con <- dbConnect(RPostgres::Postgres(), timezone = "Europe/Zurich")
    
    Sys.timezone()
    #> [1] "Europe/Zurich"
    
    dbGetQuery(con, "SHOW TIME ZONE")
    #>        TimeZone
    #> 1 Europe/Zurich
    
    dbExecute(con, "
      CREATE TABLE tz_test(
        ts_naked TIMESTAMP,
        ts_tz TIMESTAMP WITH TIME ZONE
      )
    ")
    #> [1] 0
    
    dbExecute(con, "
      INSERT INTO tz_test (ts_naked, ts_tz)
      VALUES
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00+0000',
        TIMESTAMP '2016-08-12 10:00:00+0000'
      ),
      (
        TIMESTAMP '2016-08-12 10:00:00+0000',
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00+0000'
      ),
      (
        TIMESTAMP '2016-08-12 10:00:00',
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00'
      ),
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00',
        TIMESTAMP '2016-08-12 10:00:00'
      )
    ")
    #> [1] 4
    
    r_df <- dbGetQuery(con, "SELECT * FROM tz_test")
    
    r_df$ts_naked
    #> [1] "2016-08-12 12:00:00 CEST" "2016-08-12 10:00:00 CEST"
    #> [3] "2016-08-12 10:00:00 CEST" "2016-08-12 10:00:00 CEST"
    r_df$ts_tz
    #> [1] "2016-08-12 12:00:00 CEST" "2016-08-12 14:00:00 CEST"
    #> [3] "2016-08-12 12:00:00 CEST" "2016-08-12 12:00:00 CEST"
    
    # output inserted manually here
    system("psql -c 'SELECT * FROM tz_test'")
    #>       ts_naked       |         ts_tz          
    #> ---------------------+------------------------
    #>  2016-08-12 12:00:00 | 2016-08-12 10:00:00+02
    #>  2016-08-12 10:00:00 | 2016-08-12 12:00:00+02
    #>  2016-08-12 10:00:00 | 2016-08-12 10:00:00+02
    #>  2016-08-12 10:00:00 | 2016-08-12 10:00:00+02
    #> (4 rows)
    
    dbExecute(con, "DROP TABLE tz_test")
    #> [1] 0

    Created on 2020-04-26 by the reprex package (v0.3.0)

  10. dkipb commented on Apr 27, 2020

    @dkipb
    Author

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

  11. hadley commented on Apr 27, 2020

    @hadley
    Member

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

  12. dpprdan commented on Apr 29, 2020

    @dpprdan
    Contributor

    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.

    For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone.

    When a timestamp with time zone value is output, it is always converted from UTC to the current timezone zone, and displayed as local time in that zone. To see the time in another time zone, either change timezone or use the AT TIME ZONE construct […].

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

    library(RPostgres)
    Sys.timezone()
    #> [1] "Europe/Berlin"
    con <- dbConnect(Postgres(), dbname = "postgres", timezone = "Europe/Riga")
    dbGetQuery(con, 'SHOW server_version;') # I also checked against Postgres 12.2 with identical results
    #>   server_version
    #> 1          9.6.8
    dbGetQuery(con, "SHOW TIMEZONE;")
    #>      TimeZone
    #> 1 Europe/Riga
    
    dbGetQuery(con, "SELECT '2020-04-28 00:00:01+02'::TIMESTAMPTZ;")
    #>           timestamptz
    #> 1 2020-04-28 03:00:01

    The above is 2020-04-27 22:00:01 in UTC plus 3 added by Postgres plus 2 added by RPostgres.

    dbGetQuery(con, "SELECT '2020-04-28 00:00:01+00'::TIMESTAMPTZ;")
    #>           timestamptz
    #> 1 2020-04-28 05:00:01

    The above is 2020-04-28 00:00:01 in UTC plus 3 added by Postgres plus 2 added by RPostgres.

    dbGetQuery(con, "SELECT '2020-04-28 00:00:01'::TIMESTAMPTZ;")
    #>           timestamptz
    #> 1 2020-04-28 02:00:01

    If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone.

    So the above is stored as 2020-04-27 21:00:01 in 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:

    # time with time zone
    dbGetQuery(con, "SELECT current_time;")
    #>            timetz
    #> 1 16:55:19.776205
    
    # timestamp converted to text, basically ctime
    dbGetQuery(con, "SELECT TIMEOFDAY();")
    #>                              timeofday
    #> 1 Wed Apr 29 16:55:19.784683 2020 EEST

    NOW() OTOH returns a timestamp with time zone, so also shows the problematic behaviour, i.e. adds the, in this case two hour, offset of Sys.timezone():

    dbGetQuery(con, "SELECT NOW();")
    #>                   now
    #> 1 2020-04-29 18:55:19

    Something I have not yet wrapped my head around is the behaviour of timestamp without time zone in a reprex():

    dbGetQuery(con, "SELECT '2020-04-28 00:00:01'::TIMESTAMP;")
    #>             timestamp
    #> 1 2020-04-28 01:00:01

    Usually, for a timestamp without time zone no conversions are made and it is returned ‘as-is’ by PostgreSQL.

    Conversions between timestamp without time zone and timestamp with time zone normally assume that the timestamp without time zone value should be taken or given as timezone local time.

    Same source, emphasis mine.

    Locally, i.e. in RStudio and RGUI I indeed get 2020-04-28 00:00:01, but in a reprex() the result is off by +1 hour, regardless of time zone(s) specified.

    This also affects a possible workaround for the general RPostgres issue. If one explicitly casts a timestamp with time zone to the desired output time zone, PostgreSQL apparently returns a timestamp without time zone (which I don’t fully understand because one explicitly casts it to a time zone, but 🤷‍♂️). Again, via reprex() the result is off by +1 hour, so this obviously is not a very reliable workaround.

    dbGetQuery(con, "SELECT timezone('Europe/Riga', NOW());")
    #>              timezone
    #> 1 2020-04-29 17:55:19

    Current time in Europe/Riga:

    current_tz <- Sys.getenv("TZ")
    Sys.setenv(TZ='Europe/Riga')
    Sys.timezone()
    #> [1] "Europe/Riga"
    Sys.time()
    #> [1] "2020-04-29 16:55:19 EEST"

    And just to confirm: with the UTC +3 timezone, RPostgres adds 3 hours to what PostgreSQL returns.

    dbGetQuery(con, "SELECT NOW();")
    #>                   now
    #> 1 2020-04-29 19:55:19
    
    # cleanup
    Sys.setenv(TZ=current_tz)
    dbDisconnect(con)

    Created on 2020-04-29 by the reprex package (v0.3.0)

    Session info
    devtools::session_info()
    #> - Session info ---------------------------------------------------------------
    #>  setting  value                       
    #>  version  R version 3.6.3 (2020-02-29)
    #>  os       Windows 10 x64              
    #>  system   x86_64, mingw32             
    #>  ui       RTerm                       
    #>  language en                          
    #>  collate  German_Germany.1252         
    #>  ctype    German_Germany.1252         
    #>  tz       Europe/Berlin               
    #>  date     2020-04-29                  
    #> 
    #> - Packages -------------------------------------------------------------------
    #>  package     * version     date       lib source                      
    #>  assertthat    0.2.1       2019-03-21 [1] CRAN (R 3.6.1)              
    #>  backports     1.1.6       2020-04-05 [1] CRAN (R 3.6.2)              
    #>  bit           1.1-15.2    2020-02-10 [1] CRAN (R 3.6.2)              
    #>  bit64         0.9-7       2017-05-08 [1] CRAN (R 3.6.0)              
    #>  blob          1.2.1       2020-01-20 [1] CRAN (R 3.6.2)              
    #>  callr         3.4.3       2020-03-28 [1] CRAN (R 3.6.3)              
    #>  cli           2.0.2       2020-02-28 [1] CRAN (R 3.6.3)              
    #>  crayon        1.3.4       2017-09-16 [1] CRAN (R 3.6.1)              
    #>  DBI           1.1.0       2019-12-15 [1] CRAN (R 3.6.1)              
    #>  desc          1.2.0       2018-05-01 [1] CRAN (R 3.6.1)              
    #>  devtools      2.3.0       2020-04-10 [1] CRAN (R 3.6.3)              
    #>  digest        0.6.25      2020-02-23 [1] CRAN (R 3.6.2)              
    #>  ellipsis      0.3.0       2019-09-20 [1] CRAN (R 3.6.1)              
    #>  evaluate      0.14        2019-05-28 [1] CRAN (R 3.6.1)              
    #>  fansi         0.4.1       2020-01-08 [1] CRAN (R 3.6.2)              
    #>  fs            1.4.1.9000  2020-04-15 [1] Github (r-lib/fs@0793914)   
    #>  glue          1.4.0       2020-04-03 [1] CRAN (R 3.6.2)              
    #>  highr         0.8         2019-03-20 [1] CRAN (R 3.6.1)              
    #>  hms           0.5.3       2020-01-08 [1] CRAN (R 3.6.2)              
    #>  htmltools     0.4.0       2019-10-04 [1] CRAN (R 3.6.1)              
    #>  knitr         1.28        2020-02-06 [1] CRAN (R 3.6.2)              
    #>  magrittr      1.5         2014-11-22 [1] CRAN (R 3.6.1)              
    #>  memoise       1.1.0       2017-04-21 [1] CRAN (R 3.6.1)              
    #>  pkgbuild      1.0.6       2019-10-09 [1] CRAN (R 3.6.1)              
    #>  pkgconfig     2.0.3       2019-09-22 [1] CRAN (R 3.6.1)              
    #>  pkgload       1.0.2       2018-10-29 [1] CRAN (R 3.6.1)              
    #>  prettyunits   1.1.1       2020-01-24 [1] CRAN (R 3.6.2)              
    #>  processx      3.4.2       2020-02-09 [1] CRAN (R 3.6.2)              
    #>  ps            1.3.2       2020-02-13 [1] CRAN (R 3.6.2)              
    #>  R6            2.4.1       2019-11-12 [1] CRAN (R 3.6.1)              
    #>  Rcpp          1.0.4.6     2020-04-09 [1] CRAN (R 3.6.3)              
    #>  remotes       2.1.1       2020-02-15 [1] CRAN (R 3.6.2)              
    #>  rlang         0.4.5.9000  2020-04-21 [1] Github (r-lib/rlang@a90b04b)
    #>  rmarkdown     2.1         2020-01-20 [1] CRAN (R 3.6.2)              
    #>  RPostgres   * 1.2.0       2019-12-18 [1] CRAN (R 3.6.1)              
    #>  rprojroot     1.3-2       2018-01-03 [1] CRAN (R 3.6.1)              
    #>  sessioninfo   1.1.1       2018-11-05 [1] CRAN (R 3.6.1)              
    #>  stringi       1.4.6       2020-02-17 [1] CRAN (R 3.6.2)              
    #>  stringr       1.4.0       2019-02-10 [1] CRAN (R 3.6.1)              
    #>  testthat      2.3.2       2020-03-02 [1] CRAN (R 3.6.3)              
    #>  usethis       1.6.0       2020-04-09 [1] CRAN (R 3.6.3)              
    #>  vctrs         0.2.99.9011 2020-04-21 [1] Github (r-lib/vctrs@9075991)
    #>  withr         2.2.0       2020-04-20 [1] CRAN (R 3.6.3)              
    #>  xfun          0.13        2020-04-13 [1] CRAN (R 3.6.3)              
    #>  yaml          2.2.1       2020-02-01 [1] CRAN (R 3.6.2)              
    #> 
    #> [1] C:/Users/daniel/Documents/.R/win-library
    #> [2] C:/Program Files/R/R-3.6.3/library
  13. dpprdan commented on May 4, 2020

    @dpprdan
    Contributor

    The 1 hour offset in the reprex() that I reported above, was apparently caused by me running Sys.setenv(TZ='Europe/Riga') in my main session, which gets carried through to reprex::reprex(). My native timezone is "Europe/Berlin". "Europe/Riga" is +1 relative to "Europe/Berlin". Since dbGetQuery(con, "SELECT timezone('Europe/Riga', NOW());") returns a timestamp without timezone, this 1 hour offset is added to the result, as reported in #190.

  14. iangow commented on Jun 6, 2020

    @iangow

    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 reading timestamp with time zone data into R using RPostgres.

    (The example below shows that timezone need not be set to UTC when making the connection.)

    library(DBI)
    Sys.timezone()
    #> [1] "America/New_York"
    
    con <- dbConnect(RPostgres::Postgres())
    dbExecute(con, "SET timezone TO 'America/Chicago'")
    #> [1] 0
    dbGetQuery(con, "SHOW timezone")
    #>          TimeZone
    #> 1 America/Chicago
    dbExecute(con, "DROP TABLE IF EXISTS junk")
    #> [1] 0
    query <- "CREATE TEMPORARY TABLE junk AS 
                (SELECT '2020-05-04 '::TIMESTAMPTZ AS ts)"
    res <- dbExecute(con, query)
    
    dbExecute(con, "SET timezone TO 'UTC'")
    #> [1] 0
    res <- dbGetQuery(con, "SELECT * FROM junk")
    res
    #>                    ts
    #> 1 2020-05-04 01:00:00

    Created on 2020-06-06 by the reprex package (v0.3.0)

  15. dkipb commented on Jun 6, 2020

    @dkipb
    Author

    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.

  16. added this to the 1.2.2 milestone on Dec 27, 2020
  17. krlmlr commented on Dec 27, 2020

    @krlmlr
    Member

    I'll set up a server configured with a non-UTC time zone for testing.

  18. krlmlr commented on Jan 3, 2021

    @krlmlr
    Member

    Do not fiddle with the timezone setting after establishing the connection.

    #276 now has timezone and timezone_out arguments with correct translation.

    With #276 and a slightly different reprex I see:

    library(DBI)
    
    Sys.setenv(TZ = "America/New_York")
    Sys.timezone()
    #> [1] "America/New_York"
    
    con <- dbConnect(RPostgres::Postgres(), timezone = "America/Chicago")
    dbGetQuery(con, "SHOW timezone")
    #>          TimeZone
    #> 1 America/Chicago
    
    dbExecute(con, "DROP TABLE IF EXISTS junk")
    #> [1] 0
    query <- "CREATE TEMPORARY TABLE junk AS
                (SELECT '2020-05-04 '::TIMESTAMPTZ AS ts)"
    res <- dbExecute(con, query)
    
    res <- dbGetQuery(con, "SELECT * FROM junk")
    res
    #>           ts
    #> 1 2020-05-04
    dput(res)
    #> structure(list(ts = structure(1588568400, class = c("POSIXct", 
    #> "POSIXt"), tzone = "America/Chicago")), row.names = c(NA, -1L
    #> ), class = "data.frame")

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

  19. added a commit that references this issue on Jan 3, 2021
  20. 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?

  21. dkipb commented on Jan 6, 2021

    @dkipb
    Author

    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.

    library(devtools)
    
    dev_mode(T)
    #> Dev mode: ON
    
    install_github("https://github.com/r-dbi/RPostgres", quiet=T)
    
    library(Rpostgres)
    
    con <- dbConnect(RPostgres::Postgres(), timezone = "America/Toronto")
    
    Sys.timezone()
    #> [1] "America/Toronto"
    
    dbGetQuery(con, "SHOW TIME ZONE")
    #>          TimeZone
    #> 1 America/Toronto
    
    dbExecute(con, "
      CREATE TEMPORARY TABLE tz_test(
        ts_naked TIMESTAMP,
        ts_tz TIMESTAMP WITH TIME ZONE
      )
    ")
    #> [1] 0
    
    dbExecute(con, "
      INSERT INTO tz_test (ts_naked, ts_tz)
      VALUES 
      (
        TIMESTAMP '2016-08-12 10:00:00', 
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00'
      ),
      (
        TIMESTAMP WITH TIME ZONE '2016-08-12 10:00:00',
        TIMESTAMP '2016-08-12 10:00:00'
      )
    ")
    #> [1] 2
    
    r_df <- dbGetQuery(con, "SELECT * FROM tz_test")
    
    r_df$ts_naked
    #> [1] "2016-08-12 10:00:00 EDT" "2016-08-12 10:00:00 EDT"
    
    r_df$ts_tz
    #> [1] "2016-08-12 10:00:00 EDT" "2016-08-12 10:00:00 EDT"
    
    dev_mode(F)
    #> Dev mode: OFF
    
  22. github-actions commented on Jan 7, 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 7, 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