simonthompson99
9/13/2019 - 3:27 PM

PostgreSQL date operations and formatting

[PostgreSQL date operations and formatting] Different commands to work with dates in PG #sql #oneliner

-- extract single part of date
extract(year from date) -- can be month, day, hour etc.
--e.g.
extract(hour from '1979-02-01 12:03:01')
-- returns 12

-- reduce date to unit of date, but return full date/timestamp
date_trunc('hour', date/timestamp) -- can be month, day hour, year etc.
--e.g.
date_trunc('hour', timestamp '1979-02-01 12:03:01')
--returns '1979-02-01 12:00:00'

-- Calculate age
-- extract year from the interval given by age(to_date, from_date) function
extract(year from age(age_date, dob))