--- title: "hour" slug: "dev-database-reference-sql-functions-date-time-hour" updated: 2026-10-30T18:19:01Z published: 2026-10-30T18:19:01Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-date-time-hour" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.vastdata.com/llms.txt > Use this file to discover all available pages before exploring further. # hour *Applies to VAST Cluster 5.5.* *[Functions](/develop/docs/dev-database-reference-sql-functions-index) › [Date and time functions](/develop/docs/dev-database-reference-sql-functions-date-time) › Parts of a date or time.* Returns the hour of a timestamp or time of day, from 0 to 23, or the hours of an interval. ## Syntax ``` hour(value) ``` | Argument | Type | Description | | --- | --- | --- | | `value` | `TIMESTAMP` (also `TIMESTAMP_NS`, `TIMESTAMP_MS`, `TIMESTAMP_S`), `TIME`, `DATE` or `INTERVAL` | The value to take the hour of. | **Returns:** `BIGINT`. **Same as:** `date_part('hour', value)` and `extract(hour FROM value)`; see [date_part](/develop/docs/dev-database-reference-sql-functions-date-time-date-part). ## Set up the examples The examples connect with the ADBC driver, as in [VAST Query Engine (ADBC)](/develop/docs/dev-database-integrations-adbc), and work in a schema called `docs_sql_fn_date_time_hour`. Set `QE_ENDPOINT`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `VASTDB_BUCKET` ([SQL reference](/develop/docs/dev-database-reference-sql-index#example-connect-and-use-a-transaction)), and run the blocks in order in one Python session. Below each block is the output you should see. This block connects, defines the `run()` and `plan()` helpers, and creates a table of five events. Each has a date (`d`), a timestamp (`ts`), a time of day (`t`) and a timestamp with nanoseconds (`tns`). Row 4 has no values, and row 5 is the last moment of 1969: ``` import os import re import adbc_driver_manager import adbc_driver_manager.dbapi as dbapi import adbc_driver_vastdb BUCKET = os.environ["VASTDB_BUCKET"] SCHEMA = f'"{BUCKET}/docs_sql_fn_date_time_hour"' conn = dbapi.connect( driver=adbc_driver_vastdb.get_driver_path(), db_kwargs={ "vast.db.endpoint": os.environ["QE_ENDPOINT"], "vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"], "vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"], }, autocommit=True, ) def server_message(e): """The server's message in a driver error, without the request ID or the echoed statement.""" text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e)) found = (re.search(r'message: "(.*?)", request_id', text, re.S) or re.search(r"description: (.*)\)", text, re.S)) message = found.group(1) if found else text.strip().splitlines()[-1] message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S) message = re.split(r"\\n|\n", message)[0].replace('\\"', '"') return message.replace(BUCKET, "") def run(sql): """Run one statement. Print the rows it returns, or the error.""" try: with conn.cursor() as cur: cur.execute(sql) rows = cur.fetchall() if cur.description else [] except (adbc_driver_manager.Error, OSError) as e: print(f"{type(e).__name__}: {server_message(e)}") else: print(rows) def plan(sql): """Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert.""" with conn.cursor() as cur: cur.execute("EXPLAIN " + sql) steps = cur.fetchall()[0][1] print("\n".join(line for line in steps.splitlines() if "Rows" not in line)) TABLE = f"{SCHEMA}.events" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, d DATE, ts TIMESTAMP, t TIME, tns TIMESTAMP_NS)") run(f"INSERT INTO {TABLE} VALUES " "(1, DATE '2026-02-28', TIMESTAMP '2026-02-28 23:15:00', TIME '23:15:00', " "CAST('2026-02-28 23:15:00.123456789' AS TIMESTAMP_NS)), " "(2, DATE '2026-03-01', TIMESTAMP '2026-03-01 08:30:45.123456', TIME '08:30:45.123456', " "CAST('2026-03-01 08:30:45.123456' AS TIMESTAMP_NS)), " "(3, DATE '2024-12-30', TIMESTAMP '2024-12-30 12:00:00', TIME '12:00:00', " "CAST('2024-12-30 12:00:00' AS TIMESTAMP_NS)), " "(4, NULL, NULL, NULL, NULL), " "(5, DATE '1969-12-31', TIMESTAMP '1969-12-31 23:59:59.999999', TIME '23:59:59.999999', " "CAST('1969-12-31 23:59:59.999999999' AS TIMESTAMP_NS))") ``` ``` [] [] [(5,)] ``` ## What it does `hour` returns the hour of a timestamp or time of day on the 24-hour clock: `hour(TIMESTAMP '2024-02-29 13:45:30')` and `hour(TIME '13:45:30')` are both `13`. It works on every timestamp precision (`TIMESTAMP`, `TIMESTAMP_NS`, `TIMESTAMP_MS`, `TIMESTAMP_S`). A `DATE` has no time, so its hour is always `0`. On an `INTERVAL`, `hour` returns the whole hours in its time part. It doesn't count days or months, and it doesn't wrap at 24: | Interval | `hour` | Why | | --- | --- | --- | | `INTERVAL '1 year 2 months 3 days 04:05:06.789'` | `4` | The days aren't counted | | `INTERVAL '36 hours'` | `36` | Hours aren't turned into days | | `INTERVAL '25 months 40 days 30 hours'` | `30` | | | `INTERVAL '-90 minutes'` | `-1` | A negative interval gives a negative hour | To split 36 hours into 1 day and 12 hours first, use [normalized_interval](/develop/docs/dev-database-reference-sql-functions-date-time-normalized-interval): `hour(normalized_interval(INTERVAL '36 hours'))` is `12`. For the total length of an interval in hours, use `epoch(...) / 3600`. ## NULLs and edge cases | Input | Result | | --- | --- | | A NULL value (row 4) | `NULL` | | `DATE 'infinity'`, `TIMESTAMP '-infinity'` | `NULL` | | A `DATE`: `DATE '2026-03-01'` | `0` | | `TIME '23:59:59.999999'` | `23` | | `TIME '24:00:00'` (a valid `TIME`, the end of the day) | `24` | | `INTERVAL '-90 minutes'` | `-1` | | A time with a time zone: `TIMETZ '13:45:30.123456+02:30'` | `13`: the hour as written, without applying the offset | | An untyped `NULL`: `hour(NULL)` | Error: `Could not choose a best candidate function for the function call "hour("NULL")"` | | A string | Error: `Could not choose a best candidate function`; cast it to `TIME` or `TIMESTAMP` first | | A number, boolean, `BLOB` or list | Error: `No function matches the given name and argument types`, for example `'hour(INTEGER_LITERAL)'` | The same cases, as the cluster returns them. They use the table and helpers from [Set up the examples](/develop/docs/dev-database-reference-sql-functions-date-time-hour#set-up-the-examples): ``` run(f"SELECT id, hour(ts), hour(t) FROM {TABLE} WHERE id = 4") run("SELECT hour(DATE 'infinity'), hour(TIMESTAMP '-infinity'), hour(DATE '2026-03-01'), hour(TIME '23:59:59.999999'), " "hour(TIME '24:00:00'), hour(TIMETZ '13:45:30.123456+02:30')") run("SELECT hour(INTERVAL '1 year 2 months 3 days 04:05:06.789'), hour(INTERVAL '36 hours'), " "hour(INTERVAL '25 months 40 days 30 hours'), hour(INTERVAL '-90 minutes')") run("SELECT hour(NULL)") run("SELECT hour('13:45:30')") run("SELECT hour(123)") ``` ``` [(4, None, None)] [(None, None, 0, 23, 24, 13)] [(4, 36, 30, -1)] InternalError: Binder Error: Could not choose a best candidate function for the function call "hour("NULL")". In order to select one, please add explicit type casts. InternalError: Binder Error: Could not choose a best candidate function for the function call "hour(STRING_LITERAL)". In order to select one, please add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'hour(INTEGER_LITERAL)'. You might need to add explicit type casts. ``` ## Examples The hour of each event's timestamp and time of day, and of its date: ``` run(f"SELECT id, hour(ts), hour(t), hour(d) FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, 23, 23, 0), (2, 8, 8, 0), (3, 12, 12, 0), (4, None, None, None), (5, 23, 23, 0)] ``` Keep only the events from noon onwards, by their time of day: ``` run(f"SELECT id FROM {TABLE} WHERE hour(t) >= 12 ORDER BY id LIMIT 10") ``` ``` [(1,), (3,), (5,)] ``` ## How it runs in VAST The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (`VAST_SCAN`). VAST DataBase can evaluate a comparison of a column with a constant, but not a function of a column, so `hour()` is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine computes `hour()` for each row it returns. - **In `WHERE`,** the scan sends the column for every row, and a `FILTER` step in the Query Engine computes `hour()` and keeps the rows that match. No rows are skipped in storage. The plan of the `WHERE` example shows the `FILTER` step above the scan: ``` plan(f"SELECT id FROM {TABLE} WHERE hour(t) >= 12") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #1 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ ("hour"(t) >= 12) │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ t │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **On a `TIME` column, compare the column itself.** `t >= TIME '12:00:00'` returns the same rows as `hour(t) >= 12`, and it's pushed down to VAST DataBase, so rows that don't match never leave storage. `BETWEEN` works too, for a window such as `t BETWEEN TIME '08:00:00' AND TIME '12:00:00'`. The plan has no `FILTER` step: ``` plan(f"SELECT id FROM {TABLE} WHERE t >= TIME '12:00:00'") ``` ``` ┌───────────────────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ Projections: id │ │ │ └───────────────────────────┘ ``` - **For one hour of one day, filter on a range of the raw timestamp:** `ts >= TIMESTAMP '2026-03-01 08:00:00' AND ts < TIMESTAMP '2026-03-01 09:00:00'`. - **Store the time of day, or the hour, if you filter on it across days.** `hour(ts) >= 12` for every day has no single range on `ts`. Keep the time of day in its own `TIME` column, as `t` is here, or the hour in a number column, and compare that column with a constant. ## Limitations and errors - **No time-zone support.** On a `TIMESTAMP WITH TIME ZONE` value, such as `now()`, `hour` fails with an `Extension Autoloading Error`. Cast the value to `TIMESTAMP` first; see [time zones](/develop/docs/dev-database-reference-sql-functions-date-time-time-zones). - **`TIMESTAMP_NS` just before 1970.** Row 5's `tns`, `1969-12-31 23:59:59.999999999`, gives `0`, not `23`. Store such values as `TIMESTAMP` if you need their hour. - **One argument.** `hour(ts, ts)` fails with `No function matches the given name and argument types 'hour(TIMESTAMP, TIMESTAMP)'`. ``` run(f"SELECT id, hour(tns), hour(ts) FROM {TABLE} ORDER BY id LIMIT 10") run(f"SELECT hour(ts, ts) FROM {TABLE} LIMIT 1") ``` ``` [(1, 23, 23), (2, 8, 8), (3, 12, 12), (4, None, None), (5, 0, 23)] InternalError: Binder Error: No function matches the given name and argument types 'hour(TIMESTAMP, TIMESTAMP)'. You might need to add explicit type casts. ``` ## Similar functions | Function | Returns | Result for `TIMESTAMP '2024-02-29 13:45:30.123456'` (`hour` gives `13`) | | --- | --- | --- | | [minute](/develop/docs/dev-database-reference-sql-functions-date-time-minute) | The minute, 0 to 59 | `45` | | [date_trunc](/develop/docs/dev-database-reference-sql-functions-date-time-date-trunc) with `'hour'` | The start of the hour, as a `TIMESTAMP` | `2024-02-29 13:00:00` | | [strftime](/develop/docs/dev-database-reference-sql-functions-date-time-strftime) with `'%H'` | The hour as two-digit text | `'13'` | | [epoch](/develop/docs/dev-database-reference-sql-functions-date-time-epoch) | On an interval, its whole length in seconds: divide by 3600 for hours | | On `INTERVAL '36 hours'`: `hour` gives `36`, `epoch(...) / 3600` gives `36.0`, `day` gives `0`, and `hour(normalized_interval(...))` gives `12`. ``` run("SELECT hour(TIMESTAMP '2024-02-29 13:45:30.123456'), minute(TIMESTAMP '2024-02-29 13:45:30.123456'), " "date_trunc('hour', TIMESTAMP '2024-02-29 13:45:30.123456'), strftime(TIMESTAMP '2024-02-29 13:45:30.123456', '%H')") run("SELECT hour(INTERVAL '36 hours'), epoch(INTERVAL '36 hours') / 3600, day(INTERVAL '36 hours'), " "hour(normalized_interval(INTERVAL '36 hours'))") ``` ``` [(13, 45, datetime.datetime(2024, 2, 29, 13, 0), '13')] [(36, 36.0, 0, 12)] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] ``` ## See also - [date_part](/develop/docs/dev-database-reference-sql-functions-date-time-date-part): any part of a value, by name. - [Date and time functions](/develop/docs/dev-database-reference-sql-functions-date-time): all the date and time functions. - [Where filters run](/develop/docs/dev-database-reference-sql-select#where-filters-run) and [pushdowns](/develop/docs/dev-database-reference-pushdowns). - [EXPLAIN](/develop/docs/dev-database-reference-sql-explain): how to read a plan.