In PostgreSQL, format nonnegative whole seconds as HH:MM:SS by using integer division for hours and minutes, integer remainders for the leftover seconds, and zero-padding for display.

The result is a text representation of elapsed duration, not a clock time. Total hours remain above 23, so the format does not discard complete days when a job, recording, timer, or other activity lasts longer than one day.

convert seconds to hh mm ss in postgresql
Convert Seconds to HH:MM:SS in PostgreSQL

Convert a PostgreSQL duration column to HH:MM:SS

Use this workflow when the source field already contains a nonnegative whole-number count of elapsed seconds.

  1. Confirm the source type. Prefer an integer or bigint column so PostgreSQL performs integer division and remainder calculations without an implicit rounding step. If the value comes from a timestamp or interval calculation, use the epoch-extraction workflow below.

  2. Test the formatting expression with one value. This query calculates the total hours, remaining minutes, and final seconds, then concatenates them into one text field:

    Query: WITH durations(elapsed_seconds) AS ( VALUES (98765::bigint) ) SELECT CASE WHEN elapsed_seconds / 3600 BETWEEN 0 AND 9 THEN '0' || (elapsed_seconds / 3600)::text ELSE (elapsed_seconds / 3600)::text END || ':' || lpad(((elapsed_seconds % 3600) / 60)::text, 2, '0') || ':' || lpad((elapsed_seconds % 60)::text, 2, '0') AS hh_mm_ss FROM durations;

  3. Read the three fields. The first division produces total hours. Dividing the remaining amount by 60 produces minutes, and the final remainder produces seconds. The CASE expression gives ordinary hour values a leading zero while preserving hour values longer than two digits.

  4. Replace the test row with the database source. Change the CTE to select the relevant column from your table, retain the formatting expression, and run the SELECT. Treat hh_mm_ss as text rather than a timestamp, interval, or numeric value.

For the test row, 98,765 ÷ 3,600 = 27 with a remainder of 1,565; 1,565 ÷ 60 = 26 with a remainder of 5. The formatted result is 27:26:05. Because the hours field is not reduced modulo 24, all 27 hours remain visible.

How the PostgreSQL arithmetic works

In PostgreSQL, division between integer values produces an integer quotient. For nonnegative data, that quotient is the floor of the mathematical result. The modulo operator, written as %, returns the remainder. These two operations let the expression separate a duration without introducing floating-point tails.

Hours come from elapsed_seconds / 3600. Minutes come from the remainder after the complete hours are removed, while seconds come from the final remainder after complete minutes are removed. This construction keeps minutes and seconds between 00 and 59. Their lpad calls add a leading zero when needed, producing conventional two-digit fields.

The hour field uses a CASE expression rather than a fixed-width treatment because a long duration may require three or more hour digits. The result of the || concatenation is a PostgreSQL text value, which makes it suitable for logs, reports, CSV exports, JSON payloads, and display columns that require exactly this presentation.

The unit constants are not arbitrary. The BIPM SI Brochure — Concise Summary defines one minute as 60 seconds and one hour as 3,600 seconds, while NIST guidance on writing SI units identifies the second as the SI unit for time interval.

Approach Best fit Important behavior
PostgreSQL formatting expression Formatting values stored in database rows Returns text, preserves total hours, and uses integer field boundaries
Seconds to HMS Converter Checking or copying one literal duration Accepts a nonnegative whole number and provides an exact clipboard value
Native interval or timestamp Further date and time arithmetic Carries different type semantics and is not itself an HH:MM:SS display string

Preserve elapsed hours instead of wrapping at 24

An elapsed duration and a time of day are different concepts. A clock repeats its hour field every day, but a duration records every complete hour. Reducing the PostgreSQL hour field with modulo 24 would remove one full day for each 24 hours and make the original total impossible to recover from the formatted result.

The query above deliberately uses the total hour quotient, so a multi-day duration continues into larger hour values. Minutes and seconds still roll over normally within each hour, but the hours themselves do not roll over into a separate day field.

When communicating the result, label it as a duration when that distinction matters. If a downstream system requires both a day count and a clock-style field from 00 to 23, calculate those as separate components instead of wrapping the total hours.

Use a timestamp difference as the whole-second source

PostgreSQL can calculate an elapsed interval between two timestamps and extract its epoch value. When the display should contain only complete seconds, make the precision choice explicit with floor before converting to bigint.

Query: WITH source AS ( SELECT floor(EXTRACT(EPOCH FROM (finished_at - started_at)))::bigint AS elapsed_seconds FROM job_runs ), durations AS ( SELECT elapsed_seconds FROM source WHERE elapsed_seconds >= 0 ) SELECT CASE WHEN elapsed_seconds / 3600 BETWEEN 0 AND 9 THEN '0' || (elapsed_seconds / 3600)::text ELSE (elapsed_seconds / 3600)::text END || ':' || lpad(((elapsed_seconds % 3600) / 60)::text, 2, '0') || ':' || lpad((elapsed_seconds % 60)::text, 2, '0') AS hh_mm_ss FROM durations;

This query filters out negative values so the formatting rules stay within the nonnegative elapsed-duration scope. In a production system, use explicit error reporting when a negative interval needs investigation rather than silently discarding it.

The floor operation intentionally removes a fractional tail from the epoch extraction. If exact fractional precision matters, retain the original interval or numeric epoch value separately and use a formatter that defines millisecond or other precision rules. Do not let an implicit numeric-to-integer cast make that precision decision accidentally.

Check or copy one duration without running SQL

The Seconds to HMS Converter provides the same total-hour arithmetic for a single literal value and places the formatted result on the clipboard. It is useful for checking an expected database value, preparing a test fixture, or copying a duration into a log message. It does not execute PostgreSQL queries or read a database column.

  1. Enter one nonnegative whole number of elapsed seconds.

  2. Select Convert to HH:MM:SS and review the total-hour, minute, and second fields.

  3. Copy the formatted value using the copy button. The clipboard receives the exact displayed duration, and the hour field remains above 23 for multi-day durations.

The converter accepts whole numbers from 0 through 9,007,199,254,740,991, which is JavaScript’s largest safe integer. Decimal and negative inputs are rejected. A larger numeric input could allow adjacent integers to collapse to the same floating-point value, so the explicit ceiling favors an auditable error over a plausible but inaccurate seconds field.

That range applies to the standalone converter. A PostgreSQL query can handle the whole-second values supported by its source column type, so check the database schema separately rather than assuming the tool and column share an identical ceiling.

Validate the result before storing it

Check the conversion by reading it as three fields rather than relying only on its appearance. Total hours can contain two or more digits, minutes should be 00 through 59, and seconds should also be 00 through 59. A field outside those ranges usually indicates that the source was fractional, the wrong operator was used, or the value was not normalized as expected.

The conversion is reversible. Multiply the hour field by 3,600, multiply the minute field by 60, add the seconds field, and the original total returns exactly. This round-trip check is especially useful after exporting the formatted text and reading it back from another system.

Also verify how null and negative values are handled in the surrounding application. The formatting expression returns null when a source value is null, while negative input is outside the nonnegative duration definition. Decide whether those records should be rejected, reported, or routed to a separate signed-offset workflow.

Match the required destination format

HH:MM:SS is useful for logs, timers, exercise records, media durations, job runtimes, test output, and simple cleanup, but it is not the only duration syntax. A destination that requires ISO 8601 duration syntax needs that syntax rather than a relabeled colon string. A destination that requires days plus a 00-to-23 clock field also needs separate components.

The arithmetic itself only decomposes a stated count of elapsed seconds. It does not interpret dates, time zones, daylight saving transitions, leap seconds, or calendar months. Those concerns belong to the source timestamp or interval logic before the value reaches the formatter.