Now that you have data stored in UTC, you can query it and display it in any time zone you need. In this step, you will use the EXTRACT function and the AT TIME ZONE clause to manipulate and format your timestamps.
Step 1: Extract Parts of a Timestamp with EXTRACT
The EXTRACT function allows you to pull specific components (like year, month, hour) from a timestamp. Let's get the year for each event.
SELECT event_name, EXTRACT(YEAR FROM event_time) AS event_year FROM events;
The query extracts the year from the stored UTC timestamp.
event_name | event_year
-------------------+------------
Conference Call | 2024
Project Meeting | 2024
Follow-up Meeting | 2024
(3 rows)
Step 2: Convert Timestamps with AT TIME ZONE
To view the stored UTC time in a specific local time zone, use the AT TIME ZONE clause. Let's convert all event times back to the America/Los_Angeles time zone.
SELECT event_name, event_time AT TIME ZONE 'America/Los_Angeles' AS los_angeles_time FROM events;
This query takes the UTC event_time and displays its equivalent local time in Los Angeles.
event_name | los_angeles_time
-------------------+---------------------
Conference Call | 2024-01-20 10:00:00
Project Meeting | 2024-01-20 10:00:00
Follow-up Meeting | 2024-01-21 12:00:00
(3 rows)
As you can see, the 'Project Meeting' which occurred at 18:00:00 UTC is correctly shown as 10:00:00 in Los Angeles time.
Step 3: Combine EXTRACT and AT TIME ZONE
You can combine these features for more powerful queries. For example, to find the hour of each event as it occurred in the Europe/London time zone:
SELECT event_name, EXTRACT(HOUR FROM event_time AT TIME ZONE 'Europe/London') AS event_hour_london FROM events;
This query first converts the time to the London time zone, then extracts the hour.
event_name | event_hour_london
-------------------+-------------------
Conference Call | 18
Project Meeting | 18
Follow-up Meeting | 20
(3 rows)