Convert Date to Integer in netezza - netezza

Please help in converting the date field to integer in YYYYMMDD format
Date col- YYYY-MM-DD HH:MM:SS - 2020-05-20 00:00:00
Required output - YYYYMMDD - 20200520
IN Aginity workbench (Netezza).

Reference: https://www.ibm.com/docs/en/psfa/7.2.1?topic=extensions-conversion-functions
Get the date as string
SYSTEM.ADMIN(ADMIN)=> select to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD') as str;
STR
----------
20210101
(1 row)
Now convert from string to integer base 10
SYSTEM.ADMIN(ADMIN)=> select string_to_int(to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD'), 10) as num;
NUM
----------
20210101
(1 row)
To verify it is indeed an integer let us add 5 to it
SYSTEM.ADMIN(ADMIN)=> select string_to_int(to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD'), 10) + 5 as numplus5;
NUMPLUS5
----------
20210106
(1 row)
Replace the date time string with your column in above examples.

to_char would be helpful here.
select string_to_int(
to_char(date_column, ‘YYYYMMDD’),
10 -- the base
)
...

Related

Convert Int data type to date

The SQL server database I'm using has a field stored as an integer but it is a date. Currently it is showing 20191012. I've tried the below and it seems to convert it but I'd like to show it in 10/12/2019 format. Thanks.
CONVERT(DATE,CONVERT(VARCHAR(20),EFFDAT)) AS DATE_EFF
You first need to convert the number 20191012 to a date:
SELECT DATEFROMPARTS(
20191012 / 10000,
20191012 % 10000 / 100,
20191012 % 100
)
-- 2019-10-12 (DATE)
Then FORMAT it:
SELECT FORMAT(DATEFROMPARTS(
20191012 / 10000,
20191012 % 10000 / 100,
20191012 % 100
), 'MM/dd/yyyy')
-- 10/12/2019 (NVARCHAR)
The easier way is to convert the number to a string and do a couple of SUBSTRING()s.
DECLARE #myint int = 20191012
SELECT CAST(CAST(#myint as char(8)) as date) AS [theDate]
SELECT CONVERT(char(10), (CAST(CAST(#myint as char(10)) as date)), 101) AS [theDateStyleString]
Is one way, where the first query simply casts the data to the date datatype and the second query additionally converts to a string with the MM/DD/YYYY format. But understand that converting to a string is not the same as keeping the date datatype- since date functions and comparisons (>, <, etc) do not work correctly on strings.
This produces output:
theDate
----------
2019-10-12
theDateStyleString
------------
10/12/2019

SQL CASE if date was introduced as YYYY-DD-MM to convert it as YYYY-MM-DD

Hi i am trying to solve a problem because i get a
'Conversion failed when converting date and/or time from character string.'
So then i found out that it was because a date was like this '2018-22-10' and the format i have is YYYY-MM-DD so i was trying to make a case for this case, i found this code that might help
WHEN SUBSTRING([DateAchat],6, 2) > 12 THEN ([DateAchat], '%Y-%m-%d') .strftime("%Y-%m-%d")
to_date(T1.[DateAchat],'YYYYMMDD');
FORMAT T1.[DateAchat](getdate(), 'yyyy/MM/dd ')
In DateAchat is there the date info is stored
You can use SET DATEFORMAT combined with TRY_CONVERT function
DECLARE #t TABLE (d1 nvarchar(10));
INSERT INTO #t VALUES ('2018-22-10'), ('2018-10-22'), ('2018-10-10');
SET DATEFORMAT ydm
SELECT d2
FROM (SELECT COALESCE(try_convert(datetime, d1, 120), try_convert(datetime, d1)) AS d2
FROM #t) t1
WHERE d2 IS NOT NULL
Result
d2
-----------------------
2018-10-22 00:00:00.000
2018-10-22 00:00:00.000
2018-10-10 00:00:00.000

Bring correct date format in SSIS

I need date format in American Format i.e. 9/30/2018; 8/31/2018; 7/31/2018.. so on and so forth in SSIS. I have written the code in the format as
LEFT((DT_STR,50,1252)DATEADD("d",-DAY(GETDATE()),GETDATE()),10)
This is bringing date in 2018-09-30 which is not the proper format. I do have given the data type as "STRING" as the above code doesn't take "DATE/DATE-TIME" as data type.
I am trying to bring the previous month last date and hence the format currently being fetched is not right.
Any guesses?
Thanks!
For a format like this, the date parts will need to be extracted from the date and concatenated accordingly. The expression below will convert the date to the DD/MM/YYYY format. Since you only listed single digits for the month in your question, this example does not account for zeros and the length will vary. If you want zeros added to single digit days and months, a "0" (with quotes) will need to be appended before the day and month.
RIGHT((DT_STR, 2, 1252) DATEPART("MM", DATEADD("D",-DAY(GETDATE()),GETDATE())), 2)
+ "/" + RIGHT((DT_STR, 2, 1252) DATEPART("DD", DATEADD("D",-DAY(GETDATE()),GETDATE())), 2)
+ "/" + (DT_STR, 4, 1252) DATEPART("YYYY", DATEADD("D",-DAY(GETDATE()),GETDATE()))
How about that
DECLARE #AsStr VARCHAR(10) = '2018-09-30', --If you store it as string
#AsDate DATE = '2018-09-30'; --If you store it as date
SELECT CONVERT(VARCHAR(10), #AsDate, 101) AsStr,
CONVERT(VARCHAR(10), CAST(#AsStr AS DATE), 101) AsDate;
Returns
+------------+------------+
| AsStr | AsDate |
+------------+------------+
| 09/30/2018 | 09/30/2018 |
+------------+------------+
Or you can use FORMAT() function as
SELECT
FORMAT(CAST(#AsStr AS DATE), 'MM/dd/yyyy') FormatStr,
FORMAT(#AsDate, 'MM/dd/yyyy') FormatDate;
Returns
+------------+------------+
| FormatStr | FormatDate |
+------------+------------+
| 09/30/2018 | 09/30/2018 |
+------------+------------+
You can use DATEFROMPARTS to get the first day of the month fairly easily. Then, you can use DATEADD to subtract a day, then CONVERT to output the 101 format which is in the form MM/DD/YYYY.
For example:
DECLARE #DT_STR Date = '2018-10-23'
SELECT CONVERT(varchar, DATEADD(DAY, -1, DATEFROMPARTS(YEAR(#DT_STR), MONTH(#DT_STR), 1)), 101) AS [answer]
Produces output:
answer
09/30/2018

Can any one please tell me logic behind select DATENAME(month,29*5)

select DATENAME(month,29*5)
Can any one please tell me logic behind the above query.
How it always returns correct month name when provided month number as integer.
Datetime values in Sql server are stored on 8 bytes.
The first 4 bytes represents the date and the last 4 byte represents the time.
On the date part, date is stored as the number of days since 1900-01-01.
On the time part, it's the number of clock ticks since midnight.
There are 300 clock ticks per second, so a tick is 3.33333 milliseconds.
That's also the reason why datetime is only accurate to .003 of a second.
This query will hopefully help to explain:
SELECT CAST(0 As datetime) As Date_0,
29*5 As NumberOfDays,
CAST(29*5 as datetime) As TheDate,
DATENAME(month,29*5) As TheMonthName
Results:
Date_0 NumberOfDays TheDate TheMonthName
----------------------- ------------ ----------------------- ------------
1900-01-01 00:00:00.000 145 1900-05-26 00:00:00.000 May
As for the last part of your question, 29 (28 would work as well) is the magic number here - 30 is too big (May would be returned for 4 and 5) and 27 is too small - (September would be returned for 9 and 10).
Basically i'ts just math - get the number correctly so that each time you double it with any number between 1 and 12 will give you a number of days that sums up to a day that belongs to the correct month.
You can test it yourself using this script:
DECLARE #MagicNumber int = 28
;With cte as
(
select 1 as num
union all
select num + 1
from cte
where num < 12
)
SELECT num, DATENAME(month, #MagicNumber * num ) As TheMonthName
from cte
Just change the value of #MagicNumber and see the results you get.
I think I will able to explain.
The default year-month-day for any date data type is 1900-01-01. If we consider above select query, it add 29*5 days into default date and gives the MONTHNAME.
Select DATENAME(month,29*5)
Now understand the DATENAME
DateName - Returns a character string that represents the specified datepart of the specified date. Its have different -2 argument and give the different-2 result as per datepart.
Argument 1 - Is the part of the date to return.
Argument 2 - Is a any date (Is an expression that can be resolved to a
time, date, smalldatetime, datetime, datetime2, or datetimeoffset
value.)
Here we given month as a first argument. Which means it return monthname.
The calculation of 29*5 gives 145 answer and if we simply cast into date it consider as a days and calculate as 1900-01-01 + 145 and gives the date 1900-05-26 00:00:00.000.
Means if we get the month of this will give the 5 - MAY as a answer.
Execute this query and check the answer for the above logic.
Select DATENAME(month,29*5), (29*5) , DATENAME(month, '12:10:30.123'), DATENAME(month, getdate())
select cast (145 as datetime)
DECLARE #t datetime = '12:10:30.123';
SELECT DATENAME(month, 29*5), 145/30.00;
Check for further.
MSDN Link
Convert Month Number to Month Name Function in SQL (check the #user275683 answer)
If you are simply want to show the month corresponding to month number then you should have to use like this.
declare #intMonth as int
set #intMonth = 5
Select DateName( month , DateAdd( month , #intMonth , -1 ))

how to get time in millisecond from date field of oracle for the date 01-01-9999

I want to get milliseconds from date field of oracle for date "01-01-9999".
I have created below block to achieve the same.
set serveroutput on;
declare
base_point constant timestamp := to_timestamp_tz('01-JAN-1970 00:00:00.000+00:00', 'DD-Mon-RR HH24:MI:SS.FFTZH:TZM') AT TIME ZONE 'UTC';
now timestamp := to_timestamp_tz('01-01-2099 00:00:00.000+00:00', 'DD-MM-RR HH24:MI:SS.FFTZH:TZM') AT TIME ZONE 'UTC';
-- now constant timestamp := systimestamp AT TIME ZONE 'UTC' ;
n number;
begin
select to_timestamp_tz(to_char(todate,'DD-MM-YY HH24:MI:SS')||'.000+00:00','DD-MM-YY HH24:MI:SS.FFTZH:TZM')
into now
from t_table where ACCOUNTID = 'ACC001124211';
DBMS_OUTPUT.put_line(' now :'||now);
n := (
((extract(day from (now-base_point)))*86400)
+ ((extract(hour from (now-base_point)))*3600)
+ ((extract(minute from (now-base_point)))*60)
+ ((extract(second from (now-base_point))))
) * 1000;
DBMS_OUTPUT.put_line(' n :'||n);
end;
/
but using above block I am getting value as 4070908800000, which is equal to date 1/1/2099 but actual date in my table is 01-01-9999
Can you please help us to get exact millisecond using date field
No need of PL/SQL, you could do it in plain SQL.
To convert a date to milliseconds since 01-JAN-1970:
SQL> SELECT to_number(DATE '9999-01-01'
2 - to_date('01-JAN-1970','DD-MON-YYYY')) * (24 * 60 * 60 * 1000) milliseconds
3 FROM dual;
MILLISECONDS
------------------
253370764800000
SQL>
The reason why you are getting wrong value is this statement.
select to_timestamp_tz(to_char(todate,'DD-MM-YY HH24:MI:SS')||'.000+00:00','DD-MM-YY HH24:MI:SS.FFTZH:TZM')
Since your format element for year is YY, to_char conversion will have only 2 digits for year.
select to_char(date'9999-01-01','DD-MM-YY HH24:MI:SS')||'.000+00:00' char_date
from dual
char_date
------------
01-01-99 00:00:00.000+00:00
When you convert this to timestamp using YY as format element, the year returned always has the same first 2 digits as the current year, which is why you get 2099 as year.
select to_char(to_timestamp_tz(to_char(date'9999-01-01','DD-MM-YY HH24:MI:SS')||'.000+00:00','DD-MM-YY HH24:MI:SS.FFTZH:TZM'),'yyyy') char_date
from dual;
char_date
------------
2099
Moral of the story:
Oracle recommends that you use the 4-digit year element (YYYY) instead of the shorter year elements for these reasons:
The 4-digit year element eliminates ambiguity.
The shorter year elements may affect query optimization because the year is not known at query compile time and can only be determined at run time.
I've posted here some methods to convert timestamp to nanoseconds and nanoseconds to timestamp. These methods are not affected by time zones and have a nanosecond precision.
You just need to adjust it to get milliseconds instead of nanoseconds.
You need to convert date to timestamp using "CAST(DATE_HERE AS TIMESTAMP)".
SELECT (EXTRACT(DAY FROM (
CAST(SYSDATE AS TIMESTAMP) --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
CAST(SYSDATE AS TIMESTAMP) --Replace line with desired timestamp
)) * 1000 AS MILLIS FROM DUAL;
MILLIS
1598447857000
I got my solution both ways::
millis to date
select to_date('1970-01-01 00','yyyy-mm-dd hh24') + (1424217600000)/1000/60/60/24 from dual;
date to millis (similar to date.getTime() in java)
SELECT to_number(to_date('18-02-2015 00','dd-mm-yyyy hh24') - to_date('01-JAN-1970','DD-MON-YYYY')) * (24 * 60 * 60 * 1000) milliseconds FROM dual;

Resources