Не требуется Python.Вот SQL UDF, который инкапсулирует логику.Вам нужно будет расширить его, если для вас важно множественное число единиц (mons
против mon
).
/*
Postgres AGE() Function
*/
CREATE OR REPLACE FUNCTION f_postgres_age(TIMESTAMP, TIMESTAMP)
RETURNS VARCHAR(64)
STABLE AS $$
-- Input: '1994-04-04 20:10:52', '2018-09-24 11:31:05'
-- Output: 24 years 5 mons 19 days 15:20:13
-- Input: '1994-10-04 20:10:52', '2019-06-12 11:31:05'
-- Output: 24 years 8 mons 7 days 15:20:13
-- Check: SELECT '1994-10-04 20:10:52'::TIMESTAMP
-- + INTERVAL '24 years' + INTERVAL '8 months' + INTERVAL '7 days'
-- + INTERVAL '15 hours' + INTERVAL '20 minutes' + INTERVAL '13 seconds';
-- Result: 2019-06-12 11:31:05
SELECT CASE WHEN DATEDIFF(year, DATE_TRUNC('year', $1)
, DATE_TRUNC('year', CASE WHEN DATEPART(month, $1) > DATEPART(month, $2)
THEN $2 - INTERVAL '1 Year' ELSE $2 END)) > 0
THEN DATEDIFF(year, DATE_TRUNC('year', $1)
, DATE_TRUNC('year', CASE WHEN DATEPART(month, $1) > DATEPART(month, $2)
THEN $2 - INTERVAL '1 Year' ELSE $2 END)) || ' years '
ELSE '' END
|| CASE WHEN ABS( DATEDIFF(month, DATE_TRUNC('month', $1), DATE_TRUNC('month', $2))
- DATEDIFF(month, DATE_TRUNC('year', $1)
, DATE_TRUNC('year', CASE WHEN DATEPART(month, $1) > DATEPART(month, $2)
THEN $2 - INTERVAL '1 Year' ELSE $2 END))) > 0
THEN DATEDIFF(month, DATE_TRUNC('month', $1), DATE_TRUNC('month', $2))
- DATEDIFF(month, DATE_TRUNC('year', $1)
, DATE_TRUNC('year', CASE WHEN DATEPART(month, $1) > DATEPART(month, $2)
THEN $2 - INTERVAL '1 Year' ELSE $2 END)) || ' mons '
ELSE '' END
|| CASE WHEN ABS( DATEDIFF(day, DATE_TRUNC('day', $1)+1, DATE_TRUNC('day', $2))
- DATEDIFF(day, DATE_TRUNC('month', $1), DATE_TRUNC('month', $2))) > 0
THEN DATEDIFF(day, DATE_TRUNC('day', $1)+1, DATE_TRUNC('day', $2))
- DATEDIFF(day, DATE_TRUNC('month', $1), DATE_TRUNC('month', $2)) || ' days '
ELSE '' END
|| TO_CHAR((TIMESTAMP 'epoch'
+ ( DATEDIFF(second, $1, DATE_TRUNC('day', $1)+1 )
+ DATEDIFF(second, DATE_TRUNC('day', $2), $2) )
* INTERVAL '1 Second '),'HH24:MI:SS') age
$$ LANGUAGE SQL
;