Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time comparison in ClickHouse

Tags:

clickhouse

Maybe I'm missing something simple, but I could not make time filtering to work.

Here is my sample query:

select toTimeZone(ts, 'Etc/GMT+2') as z
from (select toDateTime('2019-08-31 20:35:00') AS ts)
where z > '2019-08-31 20:34:00'

I would expect 0 results, but getting:

2019-08-31T18:35:00+00:00

Is it a bug, or do I misuse the toTimeZone() function?

Thanks!

like image 873
Vyacheslav Avatar asked Sep 02 '25 05:09

Vyacheslav


2 Answers

ClickHouse stores DateTime as Unix timestamp - other words without timezone. But timezone is taken into account when sql-query executed:

SELECT
    toDateTime('2019-08-31 20:35:00', 'UTC') AS origin_date,

    toTimeZone(origin_date, 'Etc/GMT+2') AS d1,
    toTypeName(d1) AS type1,
    toUnixTimestamp(d1) AS t1,

    toTimeZone(origin_date, 'UTC') AS d2,
    toTypeName(d2) AS type2,
    toUnixTimestamp(d2) AS t2
FORMAT Vertical

Row 1:
──────
origin_date: 2019-08-31 20:35:00

d1:          2019-08-31 18:35:00
type1:       DateTime('Etc/GMT+2')
t1:          1567283700 # <-- t1 == t2

d2:          2019-08-31 20:35:00
type2:       DateTime('UTC')
t2:          1567283700 # <-- t1 == t2

Your query works correctly.

To 'reset the timezone' of z-date can be used this way:

SELECT toDateTime(toString(toTimeZone(ts, 'Etc/GMT+2'))) AS z
FROM
(
    SELECT toDateTime('2019-08-31 20:35:00') AS ts
)
WHERE z > '2019-08-31 20:34:00'
like image 153
vladimir Avatar answered Sep 04 '25 23:09

vladimir


TZ is a property of the type not of the value

DESCRIBE TABLE
(
    SELECT
        toTimeZone(toDateTime('2019-08-31 20:35:00'), 'Etc/GMT+2') AS x,
        toDateTime('2019-08-31 20:35:00') AS y
)

┌─name─┬─type──────────────────┬─
│ x    │ DateTime('Etc/GMT+2') │
│ y    │ DateTime              │
└──────┴───────────────────────┴─


SELECT toTimeZone(ts, 'Etc/GMT+2') AS z
FROM
(
    SELECT toDateTime('2019-08-31 20:35:00') AS ts
)
WHERE z > toDateTime('2019-08-31 20:34:00', 'Etc/GMT+2')

Ok.

0 rows in set. Elapsed: 0.002 sec.
like image 43
Denny Crane Avatar answered Sep 04 '25 23:09

Denny Crane