how to convert a timestamp to int in sql (vertica) - sql

I have a timestamp as 2017-07-19 11:45:01and i want it to convert to int.
Query:
select cast(max(event_timestamp) as INT) from error_messages where error_level='ERROR' and user_name='git'
Error:
SQL Error [2366] [42846]: [Vertica][VJDBC](2366) ERROR: Cannot cast type timestamptz to int
[Vertica][VJDBC](2366) ERROR: Cannot cast type timestamptz to int
com.vertica.util.ServerException: [Vertica][VJDBC](2366) ERROR: Cannot cast type timestamptz to int

You have to use TIMESTAMPDIFF() this way:
SELECT TIMESTAMPDIFF(SECOND,'001-01-01 00:00:00', '2015-02-23 03:12:35');
timestampdiff
---------------
63560257955
to get the number of time units you want (SECONDs here above) since the timestamp you want...

If you want to get Unix Timestamp of that date as int than search fort that.
One option would be to calculate the range from your date to '1970-01-01' in seconds as int. This is the Unix Timestamp.

Use JULIAN_DAY function in Vertica to convert the time stamp to a integer value or number.
For more details refer Vertica documentation link: https://my.vertica.com/docs/6.1.x/HTML/index.htm#16070.htm
To extract number from date time with 1 second interval.
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-08');

Related

What kind of datestyle can this be?

I have a table with a column defined as:
"timestamp" int8 NULL,
which stores values like
'1638462043745210034'
When I try to cast it to timestamp or timestamp with time-zone
SELECT '1638462043745210034'::timestamp at time zone 'UTC' ;
it returns an error:
date/time field value out of range: "1638462043745210034" Hint:
Perhaps you need a different "datestyle" setting.
What kind of datestyle can it be and how can it be converted to a normal timestamp?
Looks like nanoseconds since the epoch:
SELECT to_timestamp(1638462043745210034 / 1000000000.0);
to_timestamp
══════════════════════════════
2021-12-02 17:20:43.74521+01
(1 row)

Convert timestamp to datetime changing format

I have a timestamp 2020-01-08T16:06:00+00:00 format value, I want to convert it to datetime format as 2020-01-08 16:06:00.
I have tried to convert to datetime, but getting error says:
failed when converting date and/or time from character string.
I would like to convert timestamp to datetime.
If you don't care about the timezone, you can use:
select convert(datetime, left('2020-01-08T16:06:00+00:00', 19))
If you're simply interested in dropping the the offset, and not converting the timestamp to local time (as the offset sets the timestamp at UTC), try this:
DECLARE #timestamp AS DATETIMEOFFSET = '2020-01-08T16:06:00+00:00' ;
SELECT CAST ( #timestamp AS DATETIME2(0) ) AS formatted_timestamp ;
(I've assumed the data type for your timestamp is DATETIMEOFFSET. But this could also work if the data type is DATETIME or DATETIME2.)

How to convert a timestamp varchar that contains a timezone to a timestamp type

I have timestamps like the following '2018-04-18T18:11:16+01:00' in varchar type and want to transform them to a timestamp type. I am having trouble using the to_timestamp(). Is there a specific way to use the to_timestamp() function that will allow me to do the transformation i want? If not, is there any other way to achieve my goal?
Doing
to_timestamp('2018-04-18T18:11:16+01:00', 'DD-MM-YYYY HH24:MI:SS')
gives an error of
Error: date/time field value out of range:
"2018-04-18T18:11:16+01:00"
I would expect varchars like '2018-04-18T18:11:16+01:00' to be transformed to 2018-04-18 17:11:16 (where type is timestamp)
demo:db<>fiddle
If you simply want to get the string into a timestamp holding the time zone:
Simply cast it into timestamp with time zone (= timestamptz) type:
SELECT '2018-04-18T18:11:16+01:00'::timestamptz
If you just want to cut the time zone part and holding the time without any further calculations: Simply cast it into type timestamp without time zone (= timestamp)
SELECT '2018-04-18T18:11:16+01:00'::timestamp
If you want to convert it into a timestamp at UTC (calculating -1) you can do:
SELECT ('2018-04-18T18:11:16+01:00' AT TIME ZONE 'UTC')::timestamp

Hive from_unixtime for milliseconds

We have a timestamp epoch column (BIGINT) stored in Hive.
We want to get Date 'yyyy-MM-dd' for this epoch.
Problem is my epoch is in milliseconds e.g. 1409535303522.
So select timestamp, from_unixtime(timestamp,'yyyy-MM-dd') gives wrong results for date as it expects epoch in seconds.
So i tried dividing it by 1000. But then it gets converted to Double and we can not apply function to it. Even CAST is not working when I try to Convert this double to Bigint.
Solved it by following query:
select timestamp, from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') from Hadoop_V1_Main_text_archieved limit 10;
The type should be double to ensure precision is not lost:
select from_unixtime(cast(1601256179170 as double)/1000.0, "yyyy-MM-dd hh:mm:ss.SSS") as event_timestamp
timestamp_ms is unixtime in milliseconds
SELECT from_unixtime(floor(CAST(timestamp_ms AS BIGINT)/1000), 'yyyy-MM-dd HH:mm:ss.SSS') as created_timestamp FROM table_name;
In the original answer you'll get string, but if you'd like to get date you need to call extra cast with date:
select
timestamp,
cast(from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') as date) as date_col
from Hadoop_V1_Main_text_archieved
limit 10;
Docs for casting dates and timestamps. For converting string to date:
cast(string as date)
If the string is in the form 'YYYY-MM-DD', then a date value corresponding to that year/month/day is returned. If the string value does not match this formate, then NULL is returned.
Date type is available only from Hive > 0.12.0 as mentioned here:
DATE (Note: Only available starting with Hive 0.12.0)

SQLite Current Timestamp with Milliseconds?

I am storing a timestamp field in a SQLite3 column as TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP and I was wondering if there was any way for it to include milliseconds in the timestamp as well?
Instead of CURRENT_TIMESTAMP, use (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')) so that your column definition become:
TIMESTAMP DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
For example:
CREATE TABLE IF NOT EXISTS event
(when_ts DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')));
To get number of milliseconds since epoch you can use julianday() with some additional calculations:
-- Julian time to Epoch MS
SELECT CAST((julianday('now') - 2440587.5)*86400000 AS INTEGER);
The following method doesn't require any multiplies or divides and should always produce the correct result, as multiple calls to get 'now' in a single query should always return the same result:
SELECT strftime('%s','now') || substr(strftime('%f','now'),4);
The generates the number of seconds and concatenates it to the milliseconds part from the current second+millisecond.
Here's a query that will generate a timestamp as a string with milliseconds:
select strftime("%Y-%m-%d %H:%M:%f", "now");
If you're really bent on using a numeric representation, you could use:
select julianday("now");
The accepted answer only gives you UTC. If you need a local time instead of UTC, use this:
strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime')