HSQLDB (HyperSQL) - how to get UNIX timestamp as a number with ms precision - sql

I'm trying to get a Java-style long timestamp, that is, UNIX timestamp with millisecond precision * 1000, which fits into a non-floating-point type (BIGINT).
I didn't find a way to get it straight from some function, like CURRENT_TIMESTAMP, unless I was okay with formatting like 20181010123059123.
So I found that this would give me something that looks like a number:
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
-- Gives: 23649115.452000
Note that I am substracting 2018-... since I only care about the delta, not the absolute date.
I am not sure if this is the simples way.
Turns out the type of this is INTERVAL, so I need to convert:
CAST(
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
AS DECIMAL(15,3)
)
-- Gives 23649115.000
Now the issue is, the precision is lost.
So I wonder: Where is the .452 lost and how can I keep it? This is what the manual says:
An interval value can be cast to a numeric type. In this case the interval value is first converted to a single-field INTERVAL type with the same field as the least significant filed of the interval value. The value is then converted to the target type. For example CAST (INTERVAL '1-11' YEAR TO MONTH AS INT) evaluates to INTERVAL '23' MONTH, and then 23.
And the ultimate question is:
How can I get UNIX timestamp-like number of milliseconds since some moment, e.g. UNIX epoch start?
My current whole SQL:
SELECT
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND,
FLOOR(
CAST(
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
AS DECIMAL(15,3)
) * 1000
)
FROM (VALUES(0));
-- Gives: 23649115.452000 | 23649115000

Turns out there's UNIX_MILLIS which I overlooked (because the broken PDF format manual prevents proper searching).
SELECT UNIX_MILLIS() FROM (VALUES(0))
Which renders my attempts above a nice excercise in intervals.
I still wonder, how should I CAST an interval to retain the milliseconds part.

Related

Interval Date to days [duplicate]

I have two timestamp columns: arrTime and depTime.
I need to find the number of munites the bus is late.
I tried the following:
SELECT RouteDate, round((arrTime-depTime)*1440,2) time_difference
FROM ...
I get the following error: inconsistent datatype . expected number but got interval day to second
How can i parse the nuber of minutes?
If i simply subtract: SELECT RouteDate, arrTime-depTime)*1440 time_difference
The result is correct but not well formatted:
time_difference
+00000000 00:01:00 0000000
The result of timestamp arithmetic is an INTERVAL datatype. You have an INTERVAL DAY TO SECOND there...
If you want the number of minutes one way would be to use EXTRACT(), for instance:
select extract( minute from interval_difference )
+ extract( hour from interval_difference ) * 60
+ extract( day from interval_difference ) * 60 * 24
from ( select systimestamp - (systimestamp - 1) as interval_difference
from dual )
Alternatively you can use a trick with dates:
select sysdate + (interval_difference * 1440) - sysdate
from (select systimestamp - (systimestamp - 1) as interval_difference
from dual )
The "trick" version works because of the operator order of precedence and the differences between date and timestamp arithmetic.
Initially the operation looks like this:
date + ( interval * number ) - date
As mentioned in the documentation:
Oracle evaluates expressions inside parentheses before evaluating those outside.
So, the first operation performed it to multiply the interval by 1,440. An interval, i.e. a discrete period of time, multiplied by a number is another discrete period of time, see the documentation on datetime and interval arithmetic. So, the result of this operation is an interval, leaving us with:
date + interval - date
The plus operator takes precedence over the minus here. The reason for this could be that an interval minus a date is an invalid operation, but the documentation also implies that this is the case (doesn't come out and say it). So, the first operation performed is date + interval. A date plus an interval is a date. Leaving just
date - date
As per the documentation, this results in an integer representing the number of days. However, you multiplied the original interval by 1,440, so this now represented 1,440 times the amount of days it otherwise would have. You're then left with the number of seconds.
It's worth noting that:
When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error. For example, the next two statements return errors:
The "trick" method will fail, rarely but it will still fail. As ever it's best to do it properly.
SELECT (arrTime - depTime) * 1440 time_difference
FROM Schedule
WHERE ...
That will get you the time difference in minutes. Of course, you can do any rounding that you might need to to get whole minutes....
Casting to DATE first returns the difference as a number, at least with the version of Oracle I tried.
round((cast(arrTime as date) - cast(depTime as date))*1440)
You could use TO_CHAR then convert back to a number. I have never tested the performance compared to EXTRACT, but the statement works with two dates instead of an interval which fit my needs.
Seconds:
(to_char(arrTime,'J')-to_char(depTime,'J'))*86400+(to_char(arrTime,'SSSSS')-to_char(depTime,'SSSSS'))
Minutes:
round((to_char(arrTime,'J')-to_char(depTime,'J'))*1440+(to_char(arrTime,'SSSSS')-to_char(depTime,'SSSSS'))/60)
J is julian day and SSSSS is seconds in day. Together they give an absolute time in seconds.

How to grab the previous hour of a timestamp(4) with TIMEZONE column?

so I have a table called Value. I am trying to derive the Value for the last hour (HR --> Timestamp(4) with TIME ZONE ) so that I can use it in a conditional statement in this Stored Procedure that I'm building. However, when i try the following, Oracle only returns a Date (01-Jan-19) rather than the previous hour (01-Jan-19 01.00.00.00000000 AM UTC). What am I doing wrong?
select hr
, hr - (1/24) as Converted
from value;
If I try the following, I return '31-DEC-16 12.00.00.000000000 AM' as the value for 'Converted' (no matter what the value for HR is):
select hr
, to_timestamp(hr - (1/24)) as converted
from value;
Which ultimately will be used as the definition of a variable in my stored procedure:
select max(value)
into v_Previous_hour
from value
where hr = hr - (1/24);
Am I missing something here? Thanks in advance.
Try this:
select hr
, cast( hr - (1/24) as timestamp) as Converted
from value;
Also, the query below is not going to do what you think it is.
select max(value)
into v_Previous_hour
from value
where hr = hr - (1/24);
Or you could use INTERVAL:
SELECT TO_CHAR(HR) AS HR,
TO_CHAR(CAST(HR - INTERVAL '1' HOUR - INTERVAL '0.233' SECOND AS TIMESTAMP(4) WITH TIME ZONE)) AS HR_MINUS_ONE_HOUR
FROM VAL;
(Here I subtracted an additional 0.233 seconds just to make sure we were dealing with timestamps, per #AlexPoole's comment on #OldProgrammer's answer).
SQLFiddle here
Oracle only returns a Date (01-Jan-19)
A date still has a time, your client just isn't showing it to you. You can use to_char() to display it explicitly:
select to_char(hr - (1/24), 'YYYY-MM-DD HH24:MI:SS') from ...
It is a date because [that's the result of timestamp - number] arithmetic, and the timestamp is implicitly converted to a date before the subtraction. But you are losing both the fractional seconds and the time zone from your original value. Even if you cast back to a plain timestamp that information isn't recovered, and if you cast back to a timestamp with time zone it imolicitly picks up the current session's time zone, so won't necessarily match.
To keep both you can do what you suggested in your answer, or
select hr - interval '1' hour from ...
In your procedure, declare a variable of the same data type, e.g. (as an nonymous block):
declare
l_hr value.hr%type;
begin
select hr - interval '1' hour
into l_hr
from value
where ... ;
...
end;
Don't be tempted to store or manipulate the value as a string, keep it as its origial data type. It will be easieer to work with, safer and more efficient.
Have a look at this table Matrix of Datetime Arithmetic
When you perform {TIMESTAMP WITH TIME ZONE} - {NUMERIC} then you get DATE value, i.e. you loose the time zone information.
Better use INTERVAL, e.g. hr - INTERVAL '1' HOUR or hr - NUMTODSINTERVAL(1, 'HOUR')
Anyway, I don't understand your question. If you ask "How to grab the previous hour of a timestamp(4) with TIMEZONE column?" then my answer would be
SELECT
EXTRACT(HOUR FROM hr - INTERVAL '1' HOUR) AS Solution_1
TO_CHAR(hr - INTERVAL '1' HOUR, 'HH24') AS Solution_2
FROM ...
Note, solution EXTRACT(HOUR FROM hr - INTERVAL '1' HOUR) always returns the hour of UTC time, whereas TO_CHAR(hr - INTERVAL '1' HOUR, 'HH24') returns hour from the stored time zone.
After 2 hours of hairpulling (and ironically after OldProgrammer was nice enough to provide me with an answer), I found a workaround:
select hr
, hr - numtodsinterval(1, 'hour') as converted
from value;

NUMTODSINTERVAL in Redshift. Convert a number to hours

My goal is to offset timestamps in table Date_times to reflect local timezones. I have a Timezone_lookup table that I use for that, which has a column utc_convert and its values are (2, -1, 5, etc.) depending on the timezone.
I used to use NUMTODSINTERVAL in Oracle to be able to convert the utc_convert values to hours so I can add/subtract from the datetimes in the Date_times table.
For Redshift I found INTERVAL, but that's only hardcoding the offset with a specific number.
I also tried:
SELECT CAST(utc as TIME)
FROM(
SELECT *
,to_char(cast(utc_convert as int)||':00:00', 'HH24') as utc
from Timezon_lookup
)
But this doesn't work as some number in the utc_convert column have negative values. Any ideas?
Have you tried multiplying the offset by an interval:
select current_timestamp + utc_convert * interval '1 hour'
In Oracle, you can use the time zone of the user's session (which means you do not need to maintain a table of time zone look-ups or compensate for daylight savings time).
SELECT FROM_TZ( your_timestamp_column, 'UTC' ) AT LOCAL
FROM Date_times
SQLFIDDLE
In RedShift you should be able to use the CONVERT_TIMEZONE( ['source_timezone',] 'target_timezone', 'timestamp') function rather adding a number of intervals. This would allow you to specify the target_timezone as a numeric offset from UTC or as a time zone name (which would automatically compensate for DST).

PGSQL convert time to second

why i get error with this code
SELECT EXTRACT(SECOND FROM TIME total_time) from tr_empl_quiz;
and i got error to with this code
SELECT EXTRACT(EPOCH FROM TIMESTAMP total_time) from tr_empl_quiz;
this is my table content tr_empl_quiz and type data is time without time zone
total_time
============
00:01:00
00:02:00
When you use the extract() function you are getting the value of the date/time part. In your examples, the seconds are zero, so that is what you get.
Postgres does support what you want, using the perhaps unintuitive name epoch. Epoch returns the number of seconds. For an date or datetime value, this is the number since 1970-01-01 (the beginning of Unix time). For a time or interval it is the total number of seconds during the period. So:
select extract(epoch from time '00:02:00')
returns 120.
Surprisingly, the documentation for epoch doesn't mention that it works on the time data type. The functionality is entirely consistent with what the function does. Either the documentation (which is generally quite excellent) overlooks time; or time is treated as an interval.
For a column in a table, you would just do:
SELECT EXTRACT(EPOCH FROM total_time)
FROM tr_empl_quiz;
or:
SELECT EXTRACT(EPOCH FROM CAST(total_time as time))
FROM tr_empl_quiz;
Depending on what you want.

SQL to extract matlab date from postgres db

I'd like to construct a query to "convert" a postgresql datetime to a matlab datenum. Experience with other DBs has shown me that converting the date on the DB side is much faster than doing it in matlab.
Matlab stores dates as number of days (including fractions) since an arbitrary epoch of a gregorian, non-existent date of 00-00-0000.
On Oracle, it's simple, because Oracle stores dates internally like matlab does, but with a different epoch.
select (date_column_name - to_date('01-Jan-0001') + 365) ...
A straightforward conversion of this to PG syntax doesn't work:
select (date_column_name - date '01-Jan-0001' + interval 365) ...
I've started with a particular day in matlab, for testing:
>> num2str(datenum('2010-10-02 12:00'))
ans =
734413.5
I've been in and out of the pg docs all day, extracting epochs and seconds, etc. And I've gotten close. Basically this gets the seconds in an interval, which I just divide by the seconds in a day:
Select cast(extract(epoch from (timestamp '2010-10-02 12:00'
- timestamp '0000-01-01 23:10'
+ interval '2 day'
)
) as real
)/(3600.0*24.0) AS MDate
answer:
734413.51111111111
But that exhibits some bizarre behavior. Adjusting the minutes from the epoch timestamp doesn't change the answer, except at one particular minute - i.e 23:09 is one answer, 23:10 is another, and it stays the same from 23:10 to 23:59. (other hours have similar behavior, though the particular "minute" is different.)
Any ideas? Maybe on another way to do this?
edit:
using 8.4.2
Well, extract(epoch from t::timestamp) will give seconds since the UNIX epoch (01 Jan 1970), and produces 1286017200 for '2010-10-02 12:00:00'.
Matlab gives 734413.5 for the same timepoint, but that's in days- so 63453326400 seconds, an offset of 62167309200.
So to convert postgres epoch time to matlab datenum, we should be able to just add that offset and convert back to days.
steve=# select (extract(epoch from '2010-10-02 12:00:00'::timestamp) + 62167309200) / (24*3600);
?column?
----------
734413.5
(1 row)
It seems that the cast was the problem.
Select extract(epoch from (timestamp '2010-10-02 12:00:01'
- timestamp '0000-01-01 00:00'
+ interval '1 day'))/(3600.0*24.0)
works like a champ.