Convert local datetime (with time zone) to a Unix timestamp in Oracle - oracle

I currently have a SQL query that returns the correct local DATETIME from a Unix TIMESTAMP column in our DB.
Here is an example using a specific TIMESTAMP of 1539961967000:
SELECT FROM_TZ(CAST(DATE '1970-01-01' + 1539961967000 * (1/24/60/60/1000) AS TIMESTAMP), 'UTC') AT TIME ZONE 'America/Denver' DATETIME
FROM dual;
which returns:
DATETIME
19-OCT-18 09.12.47.000000000 AM AMERICA/DENVER
I am having a hard time reversing this query to return a Unix TIMESTAMP starting with a local DATETIME.
Has anyone ever encountered this before?

You can convert your timestamp with timezone to UTC, and then subtract the epoch from that:
select timestamp '2018-10-19 09:12:47.0 AMERICA/DENVER'
- timestamp '1970-01-01 00:00:00.0 UTC' as diff
from dual;
which gives you an interval data type:
DIFF
----------------------
+17823 15:12:47.000000
You can then extract the elements from that, and multiply each element by an appropriate factor to convert it to milliseconds (i.e. for days, 60*60*24*1000); and then add them together:
select extract(day from diff) * 86400000
+ extract(hour from diff) * 3600000
+ extract(minute from diff) * 60000
+ extract(second from diff) * 1000 as unixtime
from (
select timestamp '2018-10-19 09:12:47.0 AMERICA/DENVER'
- timestamp '1970-01-01 00:00:00.0 UTC' as diff
from dual
);
UNIXTIME
--------------------
1539961967000
db<>fiddle
This preserves milliseconds too, if the starting timestamp has them (this converts from a 'Unix' time while preserving them):
select (timestamp '1970-01-01 00:00:00.0 UTC' + (1539961967567 * interval '0.001' second))
at time zone 'America/Denver' as denver_time
from dual;
DENVER_TIME
--------------------------------------------
2018-10-19 09:12:47.567000000 AMERICA/DENVER
then to convert back:
select extract(day from diff) * 86400000
+ extract(hour from diff) * 3600000
+ extract(minute from diff) * 60000
+ extract(second from diff) * 1000 as unixtime
from (
select timestamp '2018-10-19 09:12:47.567 AMERICA/DENVER'
- timestamp '1970-01-01 00:00:00.0 UTC' as diff
from dual
);
UNIXTIME
--------------------
1539961967567
db<>fiddle
If your starting timestamp has greater precision than that then you'll need to truncate (or round/floor/ceil/cast) to avoid having a non-integer result; this version just truncates the extracted milliseconds part:
select diff,
extract(day from diff) * 86400000
+ extract(hour from diff) * 3600000
+ extract(minute from diff) * 60000
+ trunc(extract(second from diff) * 1000) as unixtime
from (
select timestamp '2018-10-19 09:12:47.123456789 AMERICA/DENVER'
- timestamp '1970-01-01 00:00:00.0 UTC' as diff
from dual
);
DIFF UNIXTIME
------------------------- --------------------
+17823 15:12:47.123456789 1539961967123
Without that truncation (or equivalent) you'd end up with 1539961967123.456789.
I'd forgotten about the leap seconds discrepancy; if you need/want to handle that, see this answer.

The main issue is that Oracle has two ways (at least) to convert a number of seconds to an interval day-to-second - either with a function or with a simple arithmetic operation on an interval literal - but no direct way to do the reverse.
In the two queries below, first I show how to convert a UNIX timestamp (in milliseconds since the Epoch) to an Oracle timestamp, without losing milliseconds. (See my comment under your Question, where I point out that your method will lose milliseconds.) Then I show how to reverse the process.
Like you, I ignore the difference between "timestamp at UTC" and "Unix timestamp" caused by "Unix timestamp" ignoring leap seconds. Your business must determine whether that is important.
Unix timestamp to Oracle timestamp with time zone (preserving milliseconds):
with
inputs (unix_timestamp) as (
select 1539961967186 from dual
)
select from_tz(timestamp '1970-01-01 00:00:00'
+ interval '1' second * (unix_timestamp/1000), 'UTC')
at time zone 'America/Denver' as oracle_ts_with_timezone
from inputs
;
ORACLE_TS_WITH_TIMEZONE
--------------------------------------
2018-10-19 09:12:47.186 America/Denver
Oracle timestamp with time zone to Unix timestamp (preserving milliseconds):
with
sample_data (oracle_ts_with_timezone) as (
select to_timestamp_tz('2018-10-19 09:12:47.186 America/Denver',
'yyyy-mm-dd hh24:mi:ss.ff tzr') from dual
)
select ( extract(second from ts)
+ (trunc(ts, 'mi') - date '1970-01-01') * (24 * 60 * 60)
) * 1000 as unix_timestamp
from ( select cast(oracle_ts_with_timezone at time zone 'UTC'
as timestamp) as ts
from sample_data
)
;
UNIX_TIMESTAMP
----------------
1539961967186

Related

Oracle SQL convert number (that stores a timestamp) to human readable date time on select

I have a timestamp stored on a column called ts of type NUMBER(15, 0), and I want to print their corresponding human readable datetime in any human readable format, like '2022-03-15 23:08:24'.
None of what I have tried works, but the most closed thing is:
select
to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 / 1000) * ts
from my_table;
But this translates ts to a human readable date, not a datetime. I'm not able to show the hours, minutes and seconds. I think Oracle SQL has functions to translate timestamps to datetimes in a straightforward way, but it requires the timestamp is stored on a TIMESTAMP column, but in my case it's a NUMBER.
You are generating a date, which retains the time to second precision, but loses the milliseconds. You're also ignoring the time zone your ts is nominally in, which is presumably UTC - as an epoch/Unix time.
Anyway, you can change how the date is displayed by changing your session settings, or with to_char():
select
to_char(
date '1970-01-01' + (1 / 24 / 60 / 60 / 1000) * ts,
'YYYY-MM-DD HH24:MI:SS'
)
from my_table;
If you want to keep milliseconds, and preserve time zone, use a timestamp and intervals instead:
select
to_char(
timestamp '1970-01-01 00:00:00 UTC' + ((ts / 1000) * interval '1' second),
'YYYY-MM-DD HH24:MI:SS.FF3 TZR'
) as string_result
from my_table;
With an example ts value of 1655977424456, that gives result 2022-06-23 09:43:44.456 UTC
The result is still UTC. You can also convert the time to a different time zone if that's useful; for example:
select
to_char(
(timestamp '1970-01-01 00:00:00 UTC' + ((ts / 1000) * interval '1' second))
at time zone 'Europe/Madrid',
'YYYY-MM-DD HH24:MI:SS.FF3'
)
from my_table;
The same example ts value of 1655977424456 now gives 2022-06-23 11:43:44.456 EUROPE/MADRID, or just 2022-06-23 11:43:44.456 if you leave the TZR off the format model or convert to a plain timestamp.
And you should only convert to a string to display - not to store or manipulate or pass around the actual timestamp value.
db<>fiddle with some variations.

sysdate to unix timestamp [duplicate]

I have a timestamp datatype in database with format 24-JuL-11 10.45.00.000000000 AM and want to get it converted into unix timestamp, how can I get it?
This question is pretty much the inverse of Convert Unixtime to Datetime SQL (Oracle)
As Justin Cave says:
There are no built-in functions. But it's relatively easy to write
one. Since a Unix timestamp is the number of seconds since January 1,
1970
As subtracting one date from another date results in the number of days between them you can do something like:
create or replace function date_to_unix_ts( PDate in date ) return number is
l_unix_ts number;
begin
l_unix_ts := ( PDate - date '1970-01-01' ) * 60 * 60 * 24;
return l_unix_ts;
end;
As its in seconds since 1970 the number of fractional seconds is immaterial. You can still call it with a timestamp data-type though...
SQL> select date_to_unix_ts(systimestamp) from dual;
DATE_TO_UNIX_TS(SYSTIMESTAMP)
-----------------------------
1345801660
In response to your comment, I'm sorry but I don't see that behaviour:
SQL> with the_dates as (
2 select to_date('08-mar-12 01:00:00 am', 'dd-mon-yy hh:mi:ss am') as dt
3 from dual
4 union all
5 select to_date('08-mar-12', 'dd-mon-yy')
6 from dual )
7 select date_to_unix_ts(dt)
8 from the_dates
9 ;
DATE_TO_UNIX_TS(DT)
-------------------
1331168400
1331164800
SQL>
There's 3,600 seconds difference, i.e. 1 hour.
I realize an answer has already been accepted, but I think it should be made clear that the function in that answer doesn't consider the passed in date's time zone offset. A proper Unix timestamp should be calculated at GMT (+0). Oracle's to_date function assumes the passed in date is in the local time zone unless otherwise specified. This problem is exacerbated by the fact that Daylight Saving Time is a real thing. I over came this problem with the following function:
create or replace
function unix_time_from_date
(
in_date in date,
in_src_tz in varchar2 default 'America/New_York'
)
return integer
as
ut integer := 0;
tz varchar2(8) := '';
tz_date timestamp with time zone;
tz_stmt varchar2(255);
begin
/**
* This function is used to convert an Oracle DATE (local timezone) to a Unix timestamp (UTC).
*
* #author James Sumners
* #date 01 February 2012
*
* #param in_date An Oracle DATE to convert. It is assumed that this date will be in the local timezone.
* #param in_src_tz Indicates the time zone of the in_date parameter.
*
* #return integer
*/
-- Get the current timezone abbreviation (stupid DST)
tz_stmt := 'select systimestamp at time zone ''' || in_src_tz || ''' from dual';
execute immediate tz_stmt into tz_date;
select
extract(timezone_abbr from tz_date)
into tz
from dual;
-- Get the Unix timestamp
select
(new_time(in_date, tz, 'GMT') - to_date('01-JAN-1970', 'DD-MM-YYYY')) * (86400)
into ut
from dual;
return ut;
end unix_time_from_date;
I have some companion functions, unix_time and unix_time_to_date, available at http://jrfom.com/2012/02/10/oracle-and-unix-timestamps-revisited/. I can't believe Oracle has made it all the way to 11g without implementing these.
for date:
FUNCTION date_to_unix (p_date date,in_src_tz in varchar2 default 'Europe/Kiev') return number is
begin
return round((cast((FROM_TZ(CAST(p_date as timestamp), in_src_tz) at time zone 'GMT') as date)-TO_DATE('01.01.1970','dd.mm.yyyy'))*(24*60*60));
end;
for timestamp:
FUNCTION timestamp_to_unix (p_time timestamp,in_src_tz in varchar2 default 'Europe/Kiev') return number is
begin
return round((cast((FROM_TZ(p_time, in_src_tz) at time zone 'GMT') as date)-TO_DATE('01.01.1970','dd.mm.yyyy'))*(24*60*60));
end;
I'm using following method, which differs a little from other answers in that it uses sessiontimezone() function to properly get date
select
(
cast((FROM_TZ(CAST(in_date as timestamp), sessiontimezone) at time zone 'GMT') as date) -- in_date cast do GMT
-
TO_DATE('01.01.1970','dd.mm.yyyy') -- minus unix start date
)
* 86400000 -- times miliseconds in day
from dual;
This was what I came up with:
select substr(extract(day from (n.origstamp - timestamp '1970-01-01 00:00:00')) * 24 * 60 * 60 +
extract(hour from (n.origstamp - timestamp '1970-01-01 00:00:00')) * 60 * 60 +
extract(minute from (n.origstamp - timestamp '1970-01-01 00:00:00')) * 60 +
trunc(extract(second from (n.origstamp - timestamp '1970-01-01 00:00:00')),0),0,15) TimeStamp
from tablename;
FWIW
SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
For conversion between Oracle time and Unix times I use these functions.
They consider your current timezone. You should also add DETERMINISTIC keyword, for example if you like to use such function in a function-based index. Conversion between DATE and TIMESTAMP should be done implicitly by Oracle.
FUNCTION Timestamp2UnixTime(theTimestamp IN TIMESTAMP, timezone IN VARCHAR2 DEFAULT SESSIONTIMEZONE) RETURN NUMBER DETERMINISTIC IS
timestampUTC TIMESTAMP;
theInterval INTERVAL DAY(9) TO SECOND;
epoche NUMBER;
BEGIN
timestampUTC := FROM_TZ(theTimestamp, timezone) AT TIME ZONE 'UTC';
theInterval := TO_DSINTERVAL(timestampUTC - TIMESTAMP '1970-01-01 00:00:00');
epoche := EXTRACT(DAY FROM theInterval)*24*60*60
+ EXTRACT(HOUR FROM theInterval)*60*60
+ EXTRACT(MINUTE FROM theInterval)*60
+ EXTRACT(SECOND FROM theInterval);
RETURN ROUND(epoche);
END Timestamp2UnixTime;
FUNCTION UnixTime2Timestamp(UnixTime IN NUMBER) RETURN TIMESTAMP DETERMINISTIC IS
BEGIN
RETURN (TIMESTAMP '1970-01-01 00:00:00 UTC' + UnixTime * INTERVAL '1' SECOND) AT LOCAL;
END UnixTime2Timestamp;
I agree to what Wernfried Domscheit and James Sumners explained in their posts as solutions - mainly because of the timezone and summertime/wintertime issue !
One of the functions I prefer shorter and without dynamic SQL:
-- as Date
CAST ( FROM_TZ( TIMESTAMP '1970-01-01 00:00:00' + NUMTODSINTERVAL(input_date , 'SECOND') , 'GMT' ) AT TIME ZONE 'Europe/Berlin' AS DATE )
or
-- as Timestamp
FROM_TZ( to_timestamp(Date '1970-01-01' + input_date / 86400 ), 'GMT' ) AT TIME ZONE 'Europe/Berlin'
As "Time Zone" one needs to put the static string (ie 'Europe/Berlin') and not the dbtimezone or sessiontimezone variable, because this might yield a wrong offset because the execution time can be in Summer while the unix Timestamp could be in winter.
All the above do this:-
ORA-01873: the leading precision of the interval is too small
if your dates are TIMESTAMP format.
Here's the correct answer (assuming you're smart enough to have set up your server to use UTC.)
select (cast(sys_extract_utc(current_timestamp) as date) - TO_DATE('1970-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS')) * 86400 as gmt_epoch from dual;
SELECT
to_char(sysdate, 'YYYY/MM/DD HH24:MI:SS') dt,
round((sysdate - to_date('19700101 000000', 'YYYYMMDD HH24MISS'))*86400) as udt
FROM dual;

Number to Date conversion (Oracle)

I have a number that matches a date and I have no idea how the number is calculated using that date, here are three examples:
08/08/2018 12:23 73691437391180
08/08/2018 12:32 73691437976165
11/11/2015 14:41 73591349310000
If I substract the second from the first, I get the difference of 9.74975 which corresponds to the minutes (and seconds?) passed?
Thanks in advance!
PS: The data is stored in an Oracle Database. It is possible to generate more examples if needed.
Someone seems to have had some fun dreaming this up. The difference between two values does appear to be milliseconds, but they aren't obvious epoch times.
By a process of elimination it looks like a compound value, as it didn't reliably match as a single value, e.g. dividing by 60*60*24 and variants. It seems to eb based on an epoch time of 0001-01-02 00:00:00 UTC.
The first six digits seem to be the number of days since January 2nd (?) in the year 1 AD/CE. Trying a few possible epoch dates threw up:
select date '2018-08-08' - date '0001-01-01' from dual;
DATE'2018-08-08'-DATE'0001-01-01'
---------------------------------
736915
which was too close to be a coincidence, but was a day out, so it's really based on 0001-01-02, apparently.
The remaining 8 digits seem to be the number of milliseconds after midnight UTC - again just assuming it was from midnight was close, but an hour or two out. So there is also a time zone component, which perhaps make sense and matches your profile location.
This seems to work for the sample values at least:
with t (ts) as (
select timestamp '2018-08-08 11:23:11.180' from dual
union all select timestamp '2018-08-08 11:32:56.165' from dual
union all select timestamp '2015-11-11 14:41:50.000' from dual
)
select ts,
100000000 * extract(day from ts - timestamp '0001-01-02 01:00:00')
+ 3600000 * extract(hour from ts - timestamp '0001-01-02 01:00:00')
+ 60000 * extract(minute from ts - timestamp '0001-01-02 01:00:00')
+ 1000 * extract(second from ts - timestamp '0001-01-02 01:00:00') as n
from t;
N TS
-------------- -------------------------------------------
73691437391180 2018-08-08 12:23:11.180000000 EUROPE/VIENNA
73691437976165 2018-08-08 12:32:56.165000000 EUROPE/VIENNA
73591349310000 2015-11-11 14:41:50.000000000 EUROPE/VIENNA
or to convert the other way, starting from a timestamp rather than a date as there are fractional seconds and time zones involved:
with t (ts) as (
select timestamp '2018-08-08 12:23:11.180 Europe/Vienna' from dual
union all select timestamp '2018-08-08 12:32:56.165 Europe/Vienna' from dual
union all select timestamp '2015-11-11 14:41:50.000 Europe/Vienna' from dual
)
select ts,
100000000 * extract(day from ts - timestamp '0001-01-02 00:00:00 UTC')
+ 3600000 * extract(hour from ts - timestamp '0001-01-02 00:00:00 UTC')
+ 60000 * extract(minute from ts - timestamp '0001-01-02 00:00:00 UTC')
+ 1000 * extract(second from ts - timestamp '0001-01-02 00:00:00 UTC') as n
from t;
TS N
------------------------------------------- --------------
2018-08-08 12:23:11.180000000 EUROPE/VIENNA 73691437391180
2018-08-08 12:32:56.165000000 EUROPE/VIENNA 73691437976165
2015-11-11 14:41:50.000000000 EUROPE/VIENNA 73591349310000
Which is all a bit... unusual.
It's also possible, for the timestamp-to-number conversion, that the starting value is a plain timestamp; this would get the same result via implicit conversion as long as your session was in that time zone.

Unix Timestamp to ISO-8601 String

I have an Oracle table called ACQDATA with a field READDATETIME where I store a Unix timestamp in milliseconds as an INTEGER (NUMBER(38)) type.
SQL> select READDATETIME from ACQDATA where ID=1000;
READDATETIME
____________
1.4793E+12
I need to select that value as a ISO-8601 string (YYYY-MM-DDTHH:MM:SS.mmm):
SQL> select READDATETIME from ACQDATA where ID=1000;
READDATETIME
-------------------
1.4793E+12
I´ve tried to convert it using TO_CHAR, but the result is messy:
SQL> select TO_CHAR(TO_DATE('1970-01-01','YYYY-MM-DD') + NUMTODSINTERVAL(READDATETIME, 'SECOND'), 'YYYY-MM-DD HH24:MI:SS') from ACQDATA where ID=1000;
Error at line 1:
ORA-01873: the leading precision of the interval is too small
Help appreciated.
Alex's answer is not fully correct. Unix timestamp is always based on 1970-01-01 00:00:00 UTC
Unless your session runs on UTC time zone the precise solution would be like this:
select
TO_CHAR((TIMESTAMP '1970-01-01 00:00:00 UTC' + readdatetime/1000 * INTERVAL '1' SECOND) AT LOCAL, 'YYYY-MM-DD"T"HH24:MI:SS.FF3')
from ACQDATA where ID=1000;
or
select
TO_CHAR((TIMESTAMP '1970-01-01 00:00:00' AT TIME ZONE 'UTC' + readdatetime/1000 * INTERVAL '1' SECOND) AT LOCAL, 'YYYY-MM-DD"T"HH24:MI:SS.FF3')
from ACQDATA where ID=1000;
or if you prefer functions instead of literals:
select
TO_CHAR((TO_TIMESTAMP_TZ('1970-01-01 00:00:00 UTC', 'YYYY-MM-DD HH24:MI:SS TZR') + numtodsinterval(readdatetime/1000, 'SECOND')) AT LOCAL, 'YYYY-MM-DD"T"HH24:MI:SS.FF3')
from ACQDATA where ID=1000;
Your readdatetime seems to be in milliseconds. Oracle date arithmetic works on the basis of days, so you need to convert that number to the number of days it represents; one day is 86400 seconds, so it's 86400000 milliseconds:
with acqdata (id, readdatetime) as (
select 1000, 1479318995000 from dual
)
select to_char(date '1970-01-01' + (READDATETIME/86400000), 'YYYY-MM-DD"T"HH24:MI:SS')
from ACQDATA where ID=1000;
TO_CHAR(DATE'1970-0
-------------------
2016-11-16T17:56:35
The T is added as a character literal.
SQL Developer defaults to show numbers that large in scientific notation. You can change that default with set numformat, or use to_char() to show the whole value:
select readdatetime, to_char(readdatetime, '9999999999999') as string
from ACQDATA where ID=1000;
READDATETIME STRING
------------ --------------
1.4793E+12 1479318995000
If your value has fractional seconds, so the last three digits are not zeros, you can convert the date to a timestamp and add on the fractional leftovers; this also adds the UTC 'Z' indicator for fun:
with acqdata (id, readdatetime) as (
select 1000, 1479300462063 from dual
)
select to_char(cast(date '1970-01-01' + (readdatetime/86400000) as timestamp)
+ numtodsinterval(remainder(readdatetime, 1000)/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')
from acqdata where id=1000;
TO_CHAR(CAST(DATE'1970-01-01'+
------------------------------
2016-11-16T12:47:42.063Z
Or without the intermediate date value, starting from a timestamp literal:
with acqdata (id, readdatetime) as (
select 1000, 1479300462063 from dual
)
select to_char(timestamp '1970-01-01 00:00:00'
+ numtodsinterval(readdatetime/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')
from acqdata where id=1000;
TO_CHAR(TIMESTAMP'1970-0
------------------------
2016-11-16T12:47:42.063Z
As #Wernfried ponted out, it's better to explicitly show that the epoch time is starting from UTC:
alter session set time_zone='America/New_York';
with acqdata (readdatetime) as (
select 1479300462063 from dual
union all select 1467331200000 from dual
union all select 1467648000000 from dual
)
select readdatetime,
to_char(timestamp '1970-01-01 00:00:00' + numtodsinterval(readdatetime/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3') as implicit,
to_char(cast(timestamp '1970-01-01 00:00:00' as timestamp with time zone)
+ numtodsinterval(readdatetime/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3TZH:TZM') as local_offset,
to_char(timestamp '1970-01-01 00:00:00 UTC' + numtodsinterval(readdatetime/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3TZH:TZM') as utc_offset,
to_char(timestamp '1970-01-01 00:00:00 UTC' + numtodsinterval(readdatetime/1000, 'SECOND'),
'YYYY-MM-DD"T"HH24:MI:SS.FF3TZR') as utc
from acqdata;
READDATETIME IMPLICIT LOCAL_OFFSET UTC_OFFSET UTC
-------------- ----------------------- ----------------------------- ----------------------------- --------------------------
1479300462063 2016-11-16T12:47:42.063 2016-11-16T12:47:42.063-05:00 2016-11-16T12:47:42.063+00:00 2016-11-16T12:47:42.063UTC
1467331200000 2016-07-01T00:00:00.000 2016-07-01T01:00:00.000-04:00 2016-07-01T00:00:00.000+00:00 2016-07-01T00:00:00.000UTC
1467648000000 2016-07-04T16:00:00.000 2016-07-04T17:00:00.000-04:00 2016-07-04T16:00:00.000+00:00 2016-07-04T16:00:00.000UTC

oracle convert unix epoch time to date

The context is that there is an existing application in our product which generates and sends the EPOCH number to an existing oracle procedure & vice versa. It works in that procedure using something like this
SELECT UTC_TO_DATE (1463533832) FROM DUAL
SELECT date_to_utc(creation_date) FROM mytable
When I tried these queries it does work for me as well with Oracle 10g server (and oracle sql developer 4.x if that matters).
In the existing procedure the requirement was to save the value as date itself (time component was irrelevant), however in the new requirement I have to convert unix EPOCH value to datetime (at the hours/mins/seconds level, or better in a specific format such as dd-MMM-yyyy hh:mm:ss) in an oracle query. Strangely I am unable to find any documentation around the UTC_TO_DATE and DATE_TO_UTC functions with Google. I have looked around at all different questions on stackoverflow, but most of them are specific to programming languages such as php, java etc.
Bottom line, how to convert EPOCH to that level of time using these functions (or any other functions) in Oracle query? Additionally are those functions I am referring could be custom or specific somewhere, as I don't see any documentation or reference to this.
To convert from milliseconds from epoch (assume epoch is Jan 1st 1970):
select to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 / 1000) * 1322629200000
from dual;
11/30/2011 5:00:00 AM
To convert that date back to milliseconds:
select (to_date('11/30/2011 05:00:00', 'MM/DD/YYYY HH24:MI:SS') - to_date('19700101', 'YYYYMMDD')) * 24 * 60 * 60 * 1000
from dual;
1322629200000
If its seconds instead of milliseconds, just omit the 1000 part of the equation:
select to_date('19700101', 'YYYYMMDD') + ( 1 / 24 / 60 / 60 ) * 1322629200
from dual;
select (to_date('11/30/2011 05:00:00', 'MM/DD/YYYY HH24:MI:SS') - to_date('19700101', 'YYYYMMDD')) * 24 * 60 * 60
from dual;
Hope that helps.
Another option is to use an interval type:
SELECT TO_TIMESTAMP('1970-01-01 00:00:00.0'
,'YYYY-MM-DD HH24:MI:SS.FF'
) + NUMTODSINTERVAL(1493963084212/1000, 'SECOND')
FROM dual;
It has this advantage that milliseconds won't be cut.
If your epoch time is stored as an integer.....
And you desire the conversion to Oracle date format.
Step 1-->
Add your epoch date (1462086000) to standard 01-jan-1970. 86400 is seconds in a 24 hour period.
*Select TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 from dual*
**output is 5/1/2016 7:00:00 AM**
Step 2--> Convert it to a CHAR . This is needed for formatting before additional functions can be applied.
*Select TO_CHAR(TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 ,'yyyy-mm-dd hh24:mi:ss') from dual*
output is 2016-05-01 07:00:00
Step 3--> Now onto Timestamp conversion
Select to_timestamp(TO_CHAR(TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 ,'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd hh24:mi:ss') from dual
output is 5/1/2016 7:00:00.000000000 AM
Step 4--> Now need the TimeZone, usage of UTC
Select from_tz(to_timestamp(TO_CHAR(TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 ,'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd hh24:mi:ss'),'UTC') from dual
output is 5/1/2016 7:00:00.000000000 AM +00:00
Step 5--> If your timezone need is PST
Select from_tz(to_timestamp(TO_CHAR(TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 ,'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd hh24:mi:ss'),'UTC') at time zone 'America/Los_Angeles' TZ from dual
output is 5/1/2016 12:00:00.000000000 AM -07:00
Step 6--> Format the PST Timezone timestamp.
Select to_Char(from_tz(to_timestamp(TO_CHAR(TO_DATE('01-jan-1970', 'dd-mon-yyyy') + 1462086000/86400 ,'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd hh24:mi:ss'),'UTC') at time zone 'America/Los_Angeles' ,'DD-MON-YYYY HH24:MI:SS') TZ from dual
output is 01-MAY-2016 00:00:00
Step 7--> And finally, if your column is date datatype
Add to_DATE to the whole above Select.
Here it is for both UTC/GMT and EST;
GMT select (to_date('1970-01-01 00','yyyy-mm-dd hh24') +
(1519232926891)/1000/60/60/24) from dual;
EST select new_time(to_date('1970-01-01 00','yyyy-mm-dd hh24') +
(1519232926891)/1000/60/60/24, 'GMT', 'EST') from dual;
I thought somebody would be interested in seeing an Oracle function version of this:
CREATE OR REPLACE FUNCTION unix_to_date(unix_sec NUMBER)
RETURN date
IS
ret_date DATE;
BEGIN
ret_date:=TO_DATE('19700101','YYYYMMDD')+( 1/ 24/ 60/ 60)*unix_sec;
RETURN ret_date;
END;
/
I had a bunch of records I needed dates for so I updated my table with:
update bobfirst set entered=unix_to_date(1500000000+a);
where a is a number between 1 and 10,000,000.
A shorter method to convert timestamp to nanoseconds.
SELECT (EXTRACT(DAY FROM (
SYSTIMESTAMP --Replace line with desired timestamp --Maximum value: TIMESTAMP '3871-04-29 10:39:59.999999999 UTC'
- TIMESTAMP '1970-01-01 00:00:00 UTC') * 24 * 60) * 60 + EXTRACT(SECOND FROM
SYSTIMESTAMP --Replace line with desired timestamp
)) * 1000000000 AS NANOS FROM DUAL;
NANOS
1598434427263027000
A method to convert nanoseconds to timestamp.
SELECT TIMESTAMP '1970-01-01 00:00:00 UTC' + numtodsinterval(
1598434427263027000 --Replace line with desired nanoseconds
/ 1000000000, 'SECOND') AS TIMESTAMP FROM dual;
TIMESTAMP
26/08/20 09:33:47,263027000 UTC
As expected, above methods' results are not affected by time zones.
A shorter method to convert interval to nanoseconds.
SELECT (EXTRACT(DAY FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval --Maximum value: INTERVAL '+694444 10:39:59.999999999' DAY(6) TO SECOND(9) or up to 3871 year
) * 24 * 60) * 60 + EXTRACT(SECOND FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval
))) * 1000000000 AS NANOS FROM DUAL;
NANOS
1598434427263027000
A method to convert nanoseconds to interval.
SELECT numtodsinterval(
1598434427263027000 --Replace line with desired nanoseconds
/ 1000000000, 'SECOND') AS INTERVAL FROM dual;
INTERVAL
+18500 09:33:47.263027
As expected, millis, micros and nanos are converted and reverted, dispite of SYSTIMESTAMP doesn't have nanosecounds information.
Replace 1000000000 by 1000, for example, if you'd like to work with milliseconds instead of nanoseconds.
I've tried some of posted methods, but almost of them are affected by the time zone or result on data loss after revertion, so I've decided do post the methods that works for me.

Resources