Search code examples
postgresqlgopsql

postgres query not working with time format "2005-06-10 23:00:00 +0000 UTC"


Schema of my postgres table

column type
id int
name string
created timestamp without timezone

Now i am trying to fetch records which were created after a certain time. In my query if I write condition as below , it works flawlessly

created > 2009-11-10 23:00:00 +0000

but when i write the below timestamp string, it does not seems to work

created > 2009-11-10 23:00:00 +0000 UTC

The above is the default format which is obtained when i convert a time.Time object to string in Go. Does postgres not support or understand the latter format?


Solution

  • Do not use time.Time.String() because "the returned string is meant for debugging." There is no reason to expect Go's debugging representation for Time values to match anything Postgres (or any other software, for that matter) understands.

    Let the database driver worry about how to encode Time values by using a placeholder in the query and passing the time.Time value as-is:

    var t time.Time = ...
    
    rows, err := db.Query("SELECT * FROM table WHERE created > $1", t)
    // Since you're using timestamp without timezone you may want to use t.UTC(), t.Local(), or t.In(location) instead of just t.