Skip to content

Timestamp without time zone problem #221

Closed

Description

@tp2750

I have a database with a column of type "timestamp without time zone".

Times reported by that column are converted to the local timezone by RPostgres even though the server runs UTC.

Here's an example:

library(DBI)
con <- dbConnect(RPostgres::Postgres())
    
print.default(dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp) AS timestamp")$timestamp)
#> [1] 1275343200
#> attr(,"class")
#> [1] "POSIXct" "POSIXt" 
    
print.default(dbGetQuery(con, "SELECT extract(epoch from CAST('2010-06-01 00:00:00' AS timestamp)) as epoch")$epoch)
#> [1] 1275350400

The last value is the correct epoch for 2010-06-01 00:00:00 UTC.

I think the problem is related to as.POSIXct having tz="" as default, ie converting using the local timezone, but RPostgres uses "UTC" in the connection by default.

At least this shows the same:

print.default(as.POSIXct("2010-06-01 00:00:00"))
#> [1] 1275343200
#> attr(,"class")
#> [1] "POSIXct" "POSIXt" 
#> attr(,"tzone")
#> [1] ""

print.default(as.POSIXct("2010-06-01 00:00:00", tz="UTC"))
#> [1] 1275350400
#> attr(,"class")
#> [1] "POSIXct" "POSIXt" 
#> attr(,"tzone")
#> [1] "UTC"

I suggest RPostgres should use as.POSIXct() with tz="UTC" (actually the value of timezone in dbConnect) when converting values from a column of type "timestamp without time zone".

The problem goes away if timestamp with time zone is used:

print.default(dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp with time zone) AS timestamp")$timestamp)
#> [1] 1275350400
#> attr(,"class")
#> [1] "POSIXct" "POSIXt" 

Session info:

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.5 LTS

Matrix products: default
BLAS: /usr/lib/openblas-base/libblas.so.3
LAPACK: /usr/lib/libopenblasp-r0.2.18.so

locale:
 [1] LC_CTYPE=en_DK.UTF-8       LC_NUMERIC=C               LC_TIME=en_DK.UTF-8        LC_COLLATE=en_DK.UTF-8    
 [5] LC_MONETARY=en_DK.UTF-8    LC_MESSAGES=en_DK.UTF-8    LC_PAPER=en_DK.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_DK.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] futile.logger_1.4.3 RPostgres_1.1.1    

loaded via a namespace (and not attached):
 [1] bit_1.1-14           compiler_3.5.1       formatR_1.5          hms_0.4.2            DBI_1.0.0           
 [6] tools_3.5.1          lambda.r_1.2.3       yaml_2.2.0           Rcpp_1.0.1           futile.options_1.0.1
[11] bit64_0.9-7          blob_1.1.1           pkgconfig_2.0.2      rlang_0.3.4         

Activity

  1. krlmlr commented on Dec 17, 2019

    @krlmlr
    Member

    Thanks. Does it help if you set the timezone argument in dbConnect()? You need the development version 1.2.0 for this, which is going to hit CRAN very soon.

  2. stephenbfroehlich commented on Apr 8, 2020

    @stephenbfroehlich

    I'm having what I think is a related problem with timestamp with timezone fields as well ... specifically when I do set the timezone argument in dbConnect.

    In pgAdmin:

    SET TIMEZONE to "America/Edmonton";
    SELECT MAX(time_stamp) FROM table;
    

    Returns: 2020-04-03 23:55:00-06

    SET TIMEZONE to "UTC";
    SELECT MAX(time_stamp) FROM table;
    

    Returns: 2020-04-04 05:55:00+00

    Now in R with RPostgres:

    db_con <- 
        dbConnect(
            Postgres(),
                host = "server",
                dbname = "db",
                user = "username",
                bigint = "integer64",
                timezone = "UTC"
         )
    
    dbGetQuery(db_con, "SHOW TIMEZONE;")
    
    max_date <- dbGetQuery(db_con, "SELECT MAX(time_stamp) FROM table;")
    

    max_date = 2020-04-04 05:55:00

    HOWEVER ...

    db_con <- 
        dbConnect(
            Postgres(),
                host = "server",
                dbname = "db",
                user = "username",
                bigint = "integer64",
                timezone = "America/Edmonton"
         )
    
    dbGetQuery(db_con, "SHOW TIMEZONE;")
    
    max_date <- dbGetQuery(db_con, "SELECT MAX(time_stamp) FROM table;")
    

    max_date = 2020-04-03 17:55:00

    So something appears to be wrong in the time zone conversion of -06. As the SHOW TIMEZONE; queries reveal, the time zone is being passed to PostgreSQL correctly, so that part is right, its in the interpretation of the output back to POSIXct where something is off.

    Workarounds:

    • Work in UTC Sys.setenv(TZ = "UTC")
    • Cast timestamp fields to ::text in PostgreSQL and then convert them using as.POSIXct() manually in R
    • use RPostgreSQL() instead ... but its slower.

    I'll dig in to your code a little later and see if I can find it on the R side, but if its in C, I'm pretty useless to help.

  3. stephenbfroehlich commented on Apr 8, 2020

    @stephenbfroehlich

    It appears to be on the C++ side, so I can't help.

  4. stephenbfroehlich commented on Apr 8, 2020

    @stephenbfroehlich

    Also I believe I've seen something similar on the dbWriteTable side, but I'm not sure.

  5. stephenbfroehlich commented on Apr 8, 2020

    @stephenbfroehlich

    Finally, if it weren't a breaking change, I wish this package would have made the default timezone of dbConnect() to be Sys.getenv("TZ"). Still the library is a great resource, fast, and key to my workflow so thanks for all of your work on it ... it really enables me to use PostgreSQL as opposed to something far more elaborate for mid-sized data work (too big for RAM, too small for cluster), which is most of what I do.

  6. modified the milestones: 1.2.2, 1.2.3 on Dec 27, 2020
  7. krlmlr commented on Jan 3, 2021

    @krlmlr
    Member

    With #276:

    library(DBI)
    con <- dbConnect(RPostgres::Postgres())
    
    out <- dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp) AS timestamp")$timestamp
    out
    #> [1] "2010-06-01 UTC"
    dput(out)
    #> structure(1275350400, class = c("POSIXct", "POSIXt"), tzone = "UTC")

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

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

  10. stephenbfroehlich commented on Jan 3, 2021

    @stephenbfroehlich

    Yep its all better for me now too in 1.2.1.9001. Thanks :)

  11. tp2750 commented on Jan 4, 2021

    @tp2750
    Author

    Thanks a lot for fixing this @krlmlr !

    Now the timezone argument has the expected effect:

    > devtools::install_github("https://github.com/r-dbi/RPostgres", lib = "/tmp")
    > library(RPostgres, lib.loc="/tmp")
    > con <- dbConnect(RPostgres::Postgres())
    > print.default(dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp) AS timestamp")$timestamp)
    [1] 1275350400
    attr(,"class")
    [1] "POSIXct" "POSIXt" 
    attr(,"tzone")
    [1] "UTC"
    > con <- dbConnect(RPostgres::Postgres(), timezone = "Europe/Copenhagen")
    >  print.default(dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp) AS timestamp")$timestamp)
    [1] 1275343200
    attr(,"class")
    [1] "POSIXct" "POSIXt" 
    attr(,"tzone")
    [1] "Europe/Copenhagen"
    > sessionInfo()
    R version 3.6.3 (2020-02-29)
    Platform: x86_64-pc-linux-gnu (64-bit)
    Running under: Ubuntu 18.04.5 LTS
    
    Matrix products: default
    BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so
    
    locale:
     [1] LC_CTYPE=en_DK.UTF-8       LC_NUMERIC=C              
     [3] LC_TIME=en_DK.UTF-8        LC_COLLATE=en_DK.UTF-8    
     [5] LC_MONETARY=en_DK.UTF-8    LC_MESSAGES=en_DK.UTF-8   
     [7] LC_PAPER=en_DK.UTF-8       LC_NAME=C                 
     [9] LC_ADDRESS=C               LC_TELEPHONE=C            
    [11] LC_MEASUREMENT=en_DK.UTF-8 LC_IDENTIFICATION=C       
    
    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods   base     
    
    other attached packages:
    [1] RPostgres_1.2.1.9002
    
    loaded via a namespace (and not attached):
     [1] bit_4.0.4       compiler_3.6.3  generics_0.1.0  hms_0.5.3      
     [5] DBI_1.1.0       Rcpp_1.0.5      bit64_4.0.5     lubridate_1.7.9
     [9] vctrs_0.3.4     blob_1.2.1      pkgconfig_2.0.3 rlang_0.4.8    
    > 
    
    
  12. baderstine commented on Jan 20, 2021

    @baderstine
    Contributor

    Running the same code (RPostgres v1.3.1), I get a very very different return value for the first query but exactly the same for the second:

    >   print.default(DBI::dbGetQuery(con, "SELECT CAST('2010-06-01 00:00:00' AS timestamp) AS timestamp")$timestamp)
    [1] -58356663469
    attr(,"class")
    [1] "POSIXct" "POSIXt" 
    attr(,"tzone")
    [1] "America/Detroit"
    
    >   print.default(DBI::dbGetQuery(con, "SELECT extract(epoch from CAST('2010-06-01 00:00:00' AS timestamp)) as epoch")$epoch)
    [1] 1275350400
    
  13. 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.

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