SQL difference between two datetime columns - sql

I have a dataset with 2 columns of datetime datatype as shown here:
I want to take the difference between the two dates and I try it with this code:
Select
*,
original_due_date - due_date as difference
from
Table
However I'm not sure if the same would suffice as this is a datetime and not just date.
Any inputs would be much appreciated.
Desired output

The question was originally tagged Postgres, so this answers the original question.
Presumably, you are storing the values as timestamps. If you just want the results in days, then convert to dates and take the difference:
Select t.*,
(t.original_due_date::date - t.due_date::date) AS difference
from Table t;
If you want fractional days, then a pretty simple method is to extract the "epoch", which is measured in seconds, and use arithmetic:
Select t.*,
( extract(epoch from t.original_due_date -
extract(epoch from t.due_date
) / (24.0 * 60 * 60) AS decimal_days
from Table t;

transform timestamps to seconds (unix_timestamp), calculate difference and divide by (60*60*24) to get days
select (unix_timestamp(original_due_date, 'MM-dd-yyyy HH:mm')-unix_timestamp(due_date, 'MM-dd-yyyy HH:mm'))/(60*60*24) as difference_days
from (select '07-01-2021 00:00' as due_date, '02-10-2020 00:00' as original_due_date) t
Result:
-507

Related

How to get difference between two dates in days in postgres

Following is a query in oracle.
SELECT start_date - TO_DATE('1900-01-01','YYYY-MM-DD') FROM start_table
In oracle it gives the output 44680.3646, where start_date is 01-MAY-22.
what query would require to form to get the same output in EDB and postgresql
If you want to get the fractional part of a day, then you need to convert each value to number of seconds using EXTRACT(EPOCH FROM ...) and divide by 86400(number of seconds in 1 day) and then find the difference of the results.
SELECT extract(epoch from '2022-05-01 11:44:16'::timestamp - '1900-05-02'::timestamp) / 86400 as date
Result: 44559.489074074074
Demo in DBfiddle

How to calculate exact hours between two datetime fields?

I need to calculate hours between datetime fields and I can achieve it by simply doing
select date1,date2,(date1-date2) from table; --This gives answer in DD:HH:MM:SS format
select date1,date2,(trunc(date1)-trunc(date2))*24 --This doesn't take into account the time, it only gives hours between two dates.
Is there a way I can find the difference between date times that gives the output in Hours as a number?
The 'format' comment on your first query suggests your columns are timestamps, despite the dummy column names, as the result of subtracting two timestamps is an interval. Your second query is implicitly converting both timestamps to dates before subtracting them to get an answer as a number of days - which would be fractional if you weren't truncating them and thus losing the time portion.
You can extract the number of hours from the interval difference, and also 24 * the number of days if you expect it to exceed a day:
extract(day from (date1 - date2)) * 24 + extract(hour from (date1 - date2))
If you want to include fractional hours then you can extract and manipulate the minutes and seconds too.
You can also explicitly convert to dates, and truncate or floor after manipulation:
floor((cast(date1 as date) - cast(date2 as date)) * 24)
db<>fiddle demo
Use the DATEDIFF function in sql.
Example:
SELECT DATEDIFF(HOUR, '2021-09-05 12:00:00', GETDATE());
You can find it using the differnece of dates and multiplying with 24
select date1
,date2
,(date1-date2)*24 as diff_in_hrs
from table

Converting date format number to date and taking difference in SQL

I have a data set as below,
Same is date in "YYYYMMDD" format, I wanted to convert the columns to date format and take the difference between the same.
I used to below code
SELECT to_date(statement_date_key::text, 'yyyymmdd') AS statement_date,
to_date(paid_date_key::text, 'yyyymmdd') AS paid_date,
statement_date - paid_date AS Diff_in_days
FROM Table
WHERE Diff_in_days >= 90
;
Idea is to convert both the columns to dates, take the difference between them and filter cases where difference in days is more than 90.
Later I was informed that server is supported by HiveSQL and does not support of using ":", date time, and temp tables can not be created.
I'm currently stuck on how to go about given the constraints.
Help would be much appreciated.
Sample date for reference is provided in the link
dbfiddle
Hive is a little convoluted in its use of dates. You can use unix_timestamp() and work from there:
SELECT datediff(to_date(unix_timestamp(cast(statement_date_key as varchar(10)), 'yyyyMMdd')),
to_date(unix_timestamp(cast(paid_date_key as varchar(10)), 'yyyyMMdd'))
) as diff_in_days
FROM Table;
Note that you need to use a subquery if you want to use diff_in_days in a where clause.
Also, if you have date keys, then presumably you also have a calendar table, which should make this much simpler.
Hello You Can Use Below Query It Work Well
select * from (
select convert(date, statement_date_key) AS statement_date,
convert(date, paid_date) AS paid_date,
datediff(D, convert(date, statement_date_key), convert(date, paid_date)) as Diff_in_days
from Table
) qry
where Diff_in_days >= 90
Simple way: Function unix_timestamp(string, pattern) converts string in given format to seconds passed from unix epoch, calculate difference in seconds then divide by (60*60*24) to get difference in days.
select * from
(
select t.*,
(unix_timestamp(string(paid_date_key), 'yyyyMMdd') -
unix_timestamp(string(statement_date_key), 'yyyyMMdd'))/86400 as Diff_in_days
from Table t
) t
where Diff_in_days>=90
You may want to add abs() if the difference can be negative.
One more method using regexp_replace:
select * from
(
select t.*,
datediff(date(regexp_replace(string(paid_date_key), '(\\d{4})(\\d{2})(\\d{2})','$1-$2-$3')),
date(regexp_replace(string(statement_date_key), '(\\d{4})(\\d{2})(\\d{2})','$1-$2-$3'))) as Diff_in_days
from Table t
) t
where Diff_in_days>=90

Select entries created after a date, which have big integer timestamp

The table has a created_date column which has big integer as time stamp values. One of the time stamp looks like this 1596007131121. How can I query this?
select count(*) from user where created_date: date >='2020-08-30';
I need to query this.
You can convert that to a proper timestamp using the to_timestamp() function:
select *
from the_table
where to_timestamp(created_date/1000::bigint) >= date '2020-08-30';
But I would highly recommend to convert that column to a proper timestamp column.
I think you want:
select '1970-01-01'::timestamp + (created_date / 1000) * interval '1 second'
If you want this in a where clause, then use:
where created_date >= extract(epoch from '2020-08-30') * 1000
This has the nice feature that you can use an index.

How to convert Epoch time to date?

Hi I have a column with number datatype
the data like 1310112000 this is a date, but I don't know how to make it in an understandable format:
ex: 10-mar-2013 12:00:00 pm
Can any one please help me.
That is EPOCH time: number of seconds since Epoch(1970-01-01). Use this:
SELECT CAST(DATE '1970-01-01' + ( 1 / 24 / 60 / 60 ) * '1310112003' AS TIMESTAMP) FROM DUAL;
Result:
08-JUL-11 08.00.03.000000000 AM
Please try
select from_unixtime(floor(EPOCH_TIMESTAMP/1000)) from table;
This will give the result like E.g: 2018-03-22 07:10:45
PFB refence from MYSQL
In Microsoft SQL Server, the previous answers did not work for me. But the following does work.
SELECT created_time AS created_time_raw,
dateadd( second, created_time, CAST( '1970-01-01' as datetime ) ) AS created_time_dt
FROM person
person is a database table, and created_time is an integer field whose value is a number of seconds since epoch.
There may be other ways to do the datetime arithmetic. But this is the first thing that worked. I do not know if it is MSSQL specific.