Presto SQL: TO_UNIXTIME
Asked Answered
S

1

6

I want to convert a readable timestamp to UNIX time.

For example: I want to convert 2018-08-24 18:42:16 to 1535136136000.

Here is my syntax:

    TO_UNIXTIME('2018-08-24 06:42:16') new_year_ut

My error is:

   SYNTAX_ERROR: line 1:77: Unexpected parameters (varchar(19)) for function to_unixtime. Expected: to_unixtime(timestamp) , to_unixtime(timestamp with time zone)
Stinkpot answered 24/8, 2018 at 18:49 Comment(0)
A
10

You need to wrap the varchar in a CAST to timestamp:

to_unixtime(CAST('2018-08-24 06:42:16' AS timestamp)) -- note: returns a double

If your timestamp value doesn't have fraction of second (or you are not interested in it), you can cast to bigint to have integral result:

CAST(to_unixtime(CAST('2018-08-24 06:42:16' AS timestamp)) AS BIGINT)

If your readable timestamp value is a string in different format than the above, you would need to use date_parse or parse_datetime for the conversion. See https://trino.io/docs/current/functions/datetime.html for more information.

Note: when dealing with timestamp values, please keep in mind that: https://github.com/trinodb/trino/issues/37

Admissible answered 24/8, 2018 at 20:56 Comment(2)
Thank you @PiotrFindeisen! It is not giving me errors but it is returning ` 1.535092936E9` and what I want is 1535136136000Stinkpot
TO_UNIXTIME returns a double (as timestamp has millisecond precision), so you need a cast to bigint. Updated.Admissible

© 2022 - 2024 — McMap. All rights reserved.