AI Hints
Home›PostgreSQL Tutorial›Dates and Times
PostgreSQL · Lesson 13 of 120

Dates and Times

Date, time, timestamp.

⏱ 2 min read▶ Video at 10:38🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Orders have dates. Reviews have exact moments. Postgres has proper types for both, and lots of functions to work with them.

  • date
  • timestamp
  • Functions

Pulling dates apart

Extract pulls out one part, like the year or month. To char formats a date as text, any way you like. Run it. Each order date, split into parts, and written out nicely.

query.sqlsql
SELECT order_date,
       extract(year FROM order_date)   AS yr,
       extract(month FROM order_date)  AS mon,
       to_char(order_date, 'Dy DD Mon YYYY') AS pretty
FROM orders
ORDER BY order_id
LIMIT 3;
Output
 order_date |  yr  | mon |     pretty
------------+------+-----+-----------------
 2025-03-06 | 2025 |   3 | Thu 06 Mar 2025
 2024-11-24 | 2024 |  11 | Sun 24 Nov 2024
 2024-06-22 | 2024 |   6 | Sat 22 Jun 2024
(3 rows)

Date and time types

Date is a calendar day. Time is a time of day. Timestamp is a date and time together. Timestamp with time zone is the same, but stored as an exact moment. That last one is usually the right choice.

TypeExample
date2025-03-06
time14:30:00
timestamp2025-03-06 14:30
timestamptz2025-03-06 14:30+00

Summary

Use date for days and timestamp with time zone for moments, and extract and to char to work with them. Next, time zones.

Key takeaways
  • date
  • extract
  • to_char
Next up: timestamptz and Time Zones — one moment, many clocks