Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the timezone of a date in the WHERE clause of a Postgres SQL query

In Postgres, I always store my dates using timestamp with time zone.

For the sake of the discussion, let assume I have to store events at the time (8am, 1pm and 10pm) in Eastern Time Zone (EST -04) on the 2018-01-16. The timestamp in the database would be :

  • 8 am: "2018-01-16 12:00:00.000+00"
  • 1 pm: "2018-01-16 17:00:00.000+00"
  • 10pm: "2018-01-17 02:00:00.000+00"

How would I write a Postgres SQL query to get all events that occurred on the 2018-01-16 EST?

like image 731
sebastiengiroux Avatar asked Jan 17 '18 15:01

sebastiengiroux


People also ask

How do I change timezone in PostgreSQL?

If you have a timestamp without time zone column and you're storing timestamps as UTC, you need to tell PostgreSQL that, and then tell it to convert it to your local time zone.

How does Postgres store timestamp with timezone?

The timestamptz datatype is a time zone-aware date and time data type. PostgreSQL stores the timestamptz in UTC value. When you insert a value into a timestamptz column, PostgreSQL converts the timestamptz value into a UTC value and stores the UTC value in the table.

Does Postgres store dates as UTC?

PostgreSQL assumes your local time zone for any type containing only date or time. All timezone-aware dates and times are stored internally in UTC .


1 Answers

The AT TIME ZONE construct is your friend:

WHERE CAST((tscol AT TIME ZONE 'EST') AS date) = DATE '2018-01-16'
like image 178
Laurenz Albe Avatar answered Sep 30 '22 16:09

Laurenz Albe