Convert Time Zone in Amazon Redshift - postgresql

I have a datetime column in a redshift table. It contains date in UTC format.
So, when I am querying based on time_zone like UTC+5:30/ UTC+4:30, I want to convert the table datetime column to chosen time_zone and proceed further. It gives me wrong result.
Using this method :
CONVERT_TIMEZONE ( ['source_zone',] 'target_zone', 'timestamp')
Query Type 1: Wrong input, correct answer
SELECT id, convert_timezone('UTC+5:30','UTC', date) as converted_time, ingest_date
FROM table_name
WHERE conditions
Query Type 2: Correct input, wrong answer -> It again subtracting 5:30 from the date in column
SELECT id , convert_timezone('UTC','UTC+5:30',ingest_date) as converted_time, ingest_date
FROM table_name
WHERE conditions
Query Type 3: Wrong input, correct answer
SELECT id, convert_timezone('UTC','UTC-5:30',ingest_date) as converted_time, ingest_date
FROM table_name
WHERE conditions
How to convert / parse the UTC column into selected timezone?

In Redshift, CONVERT_TIMEZONE interprets the offset as the time from UTC. For example, an offset of +2 is equivalent to UTC–2, and an offset of -2 is equivalent to UTC+2. CONVERT_TIMEZONE does not use the prefix string when calculating the offset, even if the string represents a valid time zone. For example, 'NEWZONE+2’, 'PDT+2', and'GMT+2' all have the same result. If a string does not include an offset, then it must represent a valid time zone or CONVERT_TIMEZONE returns an error.
For converting time_zone, if you send "UTC+5:30/UTC-4:30", amazon interpreting it as "UTC-5:30 / UTC+4:30".
Now you can convert + into - and vice versa before sending it to redshift.
(http://docs.aws.amazon.com/redshift/latest/dg/CONVERT_TIMEZONE.html)

Related

How to extract data from DWH on a certain date? Is there the special pattern for this case in Postgres SQL?

Usually we use EXTRACT (FROM YEAR date_column) = 2000 (let it be 2000 year). Also we can add EXTRACT (MONTH FROM date_column) = 1 (let it be January). Also we can extract a day - EXTRACT (DAY FROM date_column) = 5 (let it 5). But is it possible to use the pattern for this data? How does it look like in Postgres SQL
Say we have the table Shipment, the columns - date_payment, quantity, sum.
I'd like to get the table that content all shipments for 01.01.2020
How to query this table with data format 'YYYY-MM-DD', not using EXTRACT-function?
If the date column is a date type then:
SELECT * FROM some_table WHERE date_col = '2020-01-01';
If the column is timestamp or timestamptz then:
SELECT * FROM some_table WHERE date_trunc('day', date_col) = '2020-01-01'
Beware that with timestamptz time zones come into play when doing the date_trunc. From here date_trunc:
When the input value is of type timestamp with time zone, the truncation is performed with respect to a particular time zone; for example, truncation to day produces a value that is midnight in that zone. By default, truncation is done with respect to the current TimeZone setting, but the optional time_zone argument can be provided to specify a different time zone. The time zone name can be specified in any of the ways described in Section 8.5.3.
For a timestamp value per the above link:
A time zone cannot be specified when processing timestamp without time zone or interval inputs. These are always taken at face value.

date and time concatenation in postgres

I wanted to get the only the hour of the time and concatenate it with the date.
here's my query
SELECT distinct TOTALIZER_METER_READINGS.date + to_char(TOTALIZER_METER_READINGS.time ,'HH')
FROM TOTALIZER_METER_READINGS
is there any other way to get the hour of the time without turning it into text?
+ is the operator to add numbers, dates or intervals.
The string concatenation operator in SQL is ||.
As you are storing date and time in two columns rather then using a single timestamp column, I would convert them to a single timestamp value, then apply to_char() on the "complete" timestamp:
Adding a time to a date returns a timestamp that can then be formatted as you want:
SELECT distinct to_char(TOTALIZER_METER_READINGS.date + TOTALIZER_METER_READINGS.time, 'yyyy-mm-dd HH')
FROM TOTALIZER_METER_READINGS
You can use EXTRACT (or the date_part function):
SELECT EXTRACT(hour FROM current_timestamp);
The result type is double precision.

Postgres Converting Data Types

I have a column saved as a character data type. This column is what I am going to be using as a date. The column goes "YYYY-MM-DD" in that format.
This is a problem because if I ever need to filter by date, I have to go
select col_1, col_2
from table
where date LIKE '2016-04%;
If I want to search for a date range, this turns into a giant complicated mess.
What is the easiest way to convert this to a "date" data type? I want it to continue to be in YYYY-MM-DD order (no timestamp).
My ultimate goal is to be able to search for dates in a format like this:
select col_1, col_2
from table
where date between 2016-01-01 AND 2016-05-31;
What do you guys recommend? I am terrified I am going to corrupt my date if I use an alter statement to convert my data type. (I have a copy of the data saved and can upload it again, but it will take forever.)
Edit: This is a VERY Large table.
Edit Part 2: I originally stored the data as a varchar data type because my dates were not uploading correctly and I got an error message when I tried to save as a date data type. The every date in this column is in the "YYYY-MM-DD" order. My solution was to save it as varchar to avoid the error message (I couldn't figure out what was wrong. I even got rid of leading and trailing spaces.)
Storing a date as a varchar was the wrong choice to begin with. It's very good that you want to change that.
The first step is to convert the columns using an ALTER TABLE statement:
alter table the_table
ALTER COLUMN col_1 TYPE date using col_1::date,
ALTER COLUMN col_2 TYPE date using col_2::date;
Note that this will fail if you have any value in those columns that cannot be convert to a correct date. If you get that you need to first fix those invalid strings before you can change the data type.
I want it to continue to be in YYYY-MM-DD order
This is a misconception. A DATE (or timestamp) does not have a "format". Once it's stored as a date you can display it in any format you want.
My ultimate goal is to be able to search for dates in a format like this:
2016-01-01 is not a valid date literal, a proper (i.e. correctly typed) date constant can be specified e.g. using date '2016-01-01' (note the single quotes!
So your query becomes:
select col_1, col_2
from table
where col_1 between date '2016-01-01' AND date '2016-05-31';
If you have a lot of queries like that you should consider creating an index on the date columns.
Regarding the date constant format:
Are you telling me that despite having the varchar data types, I can still (as of right now) search between specific dates by just typing the word date and putting single quotes between two dates
No, that's not the case. SQL is a strongly typed language and as such will only compare values of the same type.
Using an ANSI date literal (or e.g. to_date()) results in a type constant (i.e. a value with a specific data type).
The difference between date '2016-01-01' and '2016-01-01' is the same as between42(a number) and'42'` (a string).
If you compare a string with a date, you are comparing apples and oranges and the database will do an implicit data type conversion from one type to the other. This is something that should be avoided at all costs.
If you do not want to change the table, you should use the query sagi provided which explicitly converts the strings to dates and then does the comparison on (real) date values (not strings)
You can use POSTGRES TO_DATE() cast function :
SELECT col_1,col_2
FROM Your_Table
WHERE to_date(date_col,'yyyy-mm-dd') between to_date('2016-05-31','yyyy-mm-dd') and to_date('2016-01-01','yyyy-mm-dd')
What #a_horse said.
Plus, if you can't change the data type for some odd reason, to_date() is a safe option to convert the column on the column, but there is no point to use the same expression for provided constants. So:
SELECT col_1, col_2
FROM tbl
WHERE to_date(date, 'YYYY-DD-MM') BETWEEN date '2016-05-31' AND date '2016-01-01';
Or just use string literals without type. The type date is deferred from the context in this expression. And you don't even need to_date(). Since you are using ISO format already. A plain cast is safe:
WHERE date::date BETWEEN '2016-05-31' AND '2016-01-01';
Be sure to use ISO 8601 format for all date strings, so they are unambiguous and valid with any locale.
You can even have an expression index to support the query. Match the actual expression used in queries:
CREATE INDEX tbl_date_idx ON tbl ((date::date)); -- parentheses required!
But I wouldn't use the basic type name date as identifier to begin with.

Convert bigint data type to timestamp (and subsequently to date) in redshift

I need to convert the value stored in a bigint column to a date field. The first step of the conversion involves converting it to timestamp, and subsequently use the TRUNC method to convert this column to a date value.
However, my query is failing while converting the bigint value to timestamp.
The error that I'm getting is:-
Amazon Invalid operation: cannot cast type bigint to timestamp without time zone;
The query I'm trying for now is something like this:-
select ts::timestamp from events limit 1;
I was able to avoid the time zone error by using the method described in this thread: https://stackoverflow.com/a/36399361
My dates are based on epochs, and I was able to do the following:
SELECT
(TIMESTAMP 'epoch' + contract_start_date * INTERVAL '1 Second ')
FROM
table_name
SELECT TIMESTAMP 'epoch' + {column of bigint}/1000 * INTERVAL '1 second' as adate FROM tbl
If you are starting with a POSIX timestamp, and trying to get a timezone aware datetime value, you will need to supply a timezone - even if you later want to truncate the time part away. I'm not familiar with redshift, but perhaps there is a way to specify you mean UTC.

how to insert the current system date and time in oracle10g database

I have created a table with a column date_time type (varchar2 (40) ) but when i try to insert the current system date and time the doesnt work it gives error (too many values). please tell me what's wrong with the insert statement.
create table HR (type varchar2 (20), raised_by number (6), complaint varchar2 (500), date_time varchar2(40))
insert into HR values ('request',6785,'good morning',sysdate,'YYYY/MM/DD:HH:MI:SSAM')
The immediate cause of the error is that you have too many values, as the message says; that is, more elements in your values clause than there are columns. It is better to explicitly list the column names to avoid future problems and confusion, so you're really doing this:
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',sysdate,'YYYY/MM/DD:HH:MI:SSAM')
... sp you have four columns, but five values. You're trying to insert the current date/time as a string so you would need to use the to_char() function:
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',
to_char(sysdate,'YYYY/MM/DD:HH:MI:SSAM'))
But it is bad practice to store a date (or any other structured data, such as a number) as a string. As the documentation notes:
Each value manipulated by Oracle Database has a data type. The data
type of a value associates a fixed set of properties with the value.
These properties cause Oracle to treat values of one data type
differently from values of another. For example, you can add values of
NUMBER data type, but not values of RAW data type.
If you use a string then you can put invalid values in. If you use a proper DATE data type then you cannot accidentally put an invalid or confusing value in. Oracle will also be able to optimise the use of the column, and will be able to compare values safely and efficiently. Although the format you're using is better than some, using string comparison you still can't easily compare two values to see which is earlier, so you can't properly order by the date_time column for example.
Say you inserted two rows with values 2013/11/15:09:00:00AM and 2013/11/15:08:00:00PM - which is earlier? You need to look at the AM/PM marker to realise the first one is earlier; with a string comparison you'd get it wrong because 8 would be sorted before 9. Using HH24 instead of HH and AM avoids that, but would still be less efficient than a true date.
If you need to store a date with a time component you can use the DATE data type, which has precision down to the second; or if you need fractional seconds too then you can use TIMESTAMP. Then your table and insert would be:
create table HR (type varchar2 (20), raised_by number (6),
complaint varchar2 (500), date_time date);
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',sysdate);
You can still get the value in the format you wanted for display purposes as part of a query:
select type, raised_by, complaint,
to_char(date_time, 'YYYY/MM/DD:HH:MI:SSAM') as date_time
from HR
order by date_time;
TYPE RAISED_BY COMPLAINT DATE_TIME
-------------------- ---------- -------------------- ---------------------
request 6785 good morning 2013/11/15:08:44:35AM
Only treat a date as a string for display.
You can use TO_DATE() or TO_TIMESTAMP or To_char() function,
insert into HR values ('request',6785,'good morning',TO_DATE(sysdate, 'yyyy/mm/dd hh24:mi:ss'))
insert into HR values ('request',6785,'good morning',TO_TIMESTAMP(systimestamp, 'yyyy/mm/dd hh24:mi:ss'))
sysdate - It will give date with time.
systimestamp - It will give datetime with milliseconds.
To_date() - Used to convert string to date.
To_char() - Used to convert date to string.
Probably here you have to use To_char() because your table definition have varchar type for date_time column.
Use TIMESTAMP datatype for date_time. And while inserting use the current timestamp.
create table HR (type varchar2(20), raised_by number(6), complaint varchar2(500), date_time timestamp);
insert into HR values ('request',6785,'good morning', systimestamp);
For other options: http://psoug.org/reference/timestamp.html