Sikau

PostgreSQL · Day 2 · about 30 min

Dates, times and intervals

timestamptz, intervals, date_trunc and time zones.

Time is hard

Orders at 11:50 pm in Kathmandu are "tomorrow" in UTC. Reports need "per week" totals. PostgreSQL's date and time functions get this right, so your app doesn't have to.

Working with time

SELECT now(), current_date, now() AT TIME ZONE 'Asia/Kathmandu' AS kathmandu_time;

SELECT date '2026-10-09' + interval '3 days' AS later,
       timestamptz '2026-10-09 18:00+05:45' - interval '90 minutes' AS earlier,
       age(date '2026-10-09', date '2000-01-15') AS age;

SELECT name, joined, extract(month FROM joined) AS month, current_date - joined AS days_ago
FROM customers ORDER BY joined;

SELECT date_trunc('month', ordered_at) AS month, count(*) AS orders
FROM orders GROUP BY 1 ORDER BY 1;

The rest of this lesson

  • Grouping by day, week and monthexplain
  • Half-open rangesexplain
  • Result?predict
  • Which function?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of PostgreSQL