Converting Between HubSpot Unix Timestamp and SQL DateTime - sql

I am getting and posting data between HubSpot and my database.
HubSpot hold DateTime as UNIX Milliseconds and I am having trouble getting the same value when converting too and from.
(I want to store it as DateTime in my database which is why I am converting between them)
Starting value from HubSpot: 1531316462651
--FROM UNIX Starting Value TO DATETIME (This seems fine and gives me the value I would expect)
SELECT DATEADD(S, 1533046489401 / 1000, '1970-01-01T00:00:00.000')
--TO UNIX Starting Value FROM DATETIME (This doesn't give me the starting value - need help)
SELECT CAST(DATEDIFF(S, '1970-01-01T00:00:00.000', '2018-07-31 14:14:49.000') AS BIGINT) * 1000
As you can see when converting to unix from datetime, it is a different value to what I started with. I might be missing something obvious from looking at this too long (SQL Blindness I call it). Hopefully a simple resolve for someone who has done this before.
Thanks in advance.
EDIT: So I changed the first select statement and second statement so it reads like this:
--FROM UNIX TO DATETIME
SELECT DATEADD(MILLISECOND, 1531316462651 % 1000, DATEADD(SECOND, 1531316462651 / 1000, '19700101'))
--TO UNIX FROM DATETIME
SELECT (CAST(DATEDIFF(day, '1970-01-01T00:00:00.000', '2018-07-11 13:41:02.650') AS BIGINT) * 24 * 60 * 60 * 1000 +
DATEDIFF(millisecond, CAST('2018-07-11 13:41:02.650' as DATE), '2018-07-11 13:41:02.650')
)
Both return ALMOST the same value (1 Millisecond out) and I believe that is because SQL datetime rounds milliseconds in 3. So my original value 651 gets rounded to 650 when going to a datetime. I don't know how I can resolve this in SQL if anyone can help?

Microsoft has recognized this problem and created a function to solve it, DATEDIFF_BIG(). This is available since version 2016.
Before that, you need to do more complex manipulations. I think this does what you want:
SELECT (CAST(DATEDIFF(day, '1970-01-01T00:00:00.000', '2018-07-31 14:14:49.000') AS BIGINT) * 24 * 60 * 60 * 1000 +
DATEDIFF(millisecond, CAST('2018-07-31 14:14:49.000' as DATE), '2018-07-31 14:14:49.000')
)
That is, extract the days, multiply, and then extract the milliseconds from today. A day has 86,400,400 milliseconds, so this easily fits in an integer.
To get your original value, you need milliseconds in your date/time:
SELECT (CAST(DATEDIFF(day, '1970-01-01T00:00:00.000', '2018-07-31 14:14:49.000') AS BIGINT) * 24 * 60 * 60 * 1000 +
DATEDIFF(millisecond, CAST('2018-07-31 14:14:49.401' as DATE), '2018-07-31 14:14:49.401')
)

Related

Convert duration string into seconds integer

I want to turn strings that represent durations into their duration in seconds as an integer.
All of the strings are formatted in the following way:
hh:mm:ss
I was working with substrings, which I cast to integers and then multiplied with 3600, 60 or 1 respectively and in the end summed everything up.
Just like this:
SELECT
cast(substr(time_string, 1, 2) as smallint) * 3600 + cast(substr(time_string, 4, 2) as smallint) * 60 + cast(substr(time_string, 7, 2) as smallint) as seconds
from table_name
As I have to do this for multiple fields, I would be interested in a better way to achieve this result. My search for a better solution, though, fell flat so far.
I would appreciate any input or help!
Try using date_parse, cast to time and use date_diff with required unit:
select date_diff(
'second',
time '00:00:00', -- zero time
cast(date_parse('12:10:56', '%T') as time)
) seconds
Output:
seconds
43856

Convert this format of time to seconds

I have a column with data that looks like this
'1970-01-01 01:15:00.0000000'
(01(days):15(hours):00(minutes):0000000(seconds))
The date is irrelevant but I want to convert the time component to seconds. I want to output for this row to be be 140400.
If you really are abusing the datetime2 datatype, and using hours to store days, minutes to store hours, seconds to store minutes, and centiseconds to store seconds... You could do this...
DECLARE #YourDatetime datetime2(7) = '1970-01-01 01:15:00.0100000';
SELECT (DATEPART(HOUR,#YourDatetime) * 86400) +
(DATEPART(MINUTE,#YourDatetime) * 3600) +
(DATEPART(SECOND,#YourDatetime) * 60) +
(DATEPART(MILLISECOND, #YourDatetime) / 10)
But I strongly suggest you stop abusing the datetime2 data type. Hours should be hours, not days. Hopefully that's why you're trying to do what you're asking.
This, however, assumes you don't have any values with 24 or more hours, as a value like '1970-01-01 24:40:00.0100000' can't be stored in any Date and Time data type.
Looks like hour is days, minutes is hours, etc
Declare #d DATETIME2='1970-01-01 01:15:00.0000000'
Select (datepart(hour,#d)*3600*24)
+(datepart(minute,#d)*3600)
+(datepart(second,#d)*60)
Returns
140400
A reasonable interpretation of the question returns 90,900:
select datediff(second, '1969-12-31', '1970-01-01 01:15:00.0000000')
You can use datediff() to compute the number of seconds since your reference date:
datediff(s, '1970-01-01', #mydatetime)
I suspect that you actually want to start on January 1st, 1970, because that's epoch's starting point. If you really want one day before, then:
datediff(s, '1969-12-31', #mydatetime)

How can I find exact number of minutes without rounding between two dates in sql server

I am new to Sql server, I tried datediff several times but failed. All I need is the exact or precise number of minutes including fraction between two dates. E.g if the gap between two datetime fields is 40 seconds than it gives me 0.67 minutes and not 1 minute. Please help.
Take the difference in seconds and divide by 60.0:
select datediff(second, date1, date2) / 60.0 as diff_in_minutes
This should be close enough for most work. If you really want, you could use milliseconds instead of seconds.
select datediff(millisecond, date1, date2) / 60000.0 as diff_in_minutes
To get MILLISECOND accurate value
DECLARE #D1 DATETIME = '2015-04-16 21:38:02.610'
DECLARE #D2 DATETIME = '2015-04-16 21:38:29.023'
SELECT DATEDIFF(MILLISECOND, #D1, #D2)* 1.000 / ((1.66667) * POWER(10,5))
RESULT: 0.158477683044633910732

How to Sum (Time(n)) in Sql Server?

How want to use the sum of the time(n) operator so that i can calculate the overall total of the time but Sql server saying can't add the Time(n) column
i have a casted column which contain difference of two dates, and being casted as Time(n) by me. Now i want to add those column to get how much time i had used in total How much hours minute and seconds so i apply
select Sum(cast ((date1-date2) as Time(0))) from ABC_tbl
where date1 is reaching time and date2 is startingtime in Date format and i want to total of all hours
Convert the time to an integer value before you sum it (for example, seconds):
SELECT SUM(
datediff(second, '00:00:00', [TimeCol])
)
FROM
...
Replace [TimeCol] with the name of the Time(n) column. This gives you the total time in seconds, which you can then easily convert to minutes, hours, etc...
Hope this example help you.
DECLARE #A TABLE (SD TIME(0),ED TIME(0))
INSERT INTO #A VALUES
('09:01:09','17:59:09'),
('09:08:09','16:10:09'),
('08:55:05','18:00:00')
SELECT SUM(DATEDIFF(MINUTE,SD,ED)) SUM_IN_MINUTES,
SUM(DATEDIFF(HOUR,SD,ED)) SUM_IN_HOURS
FROM #A
Result:
SUM_IN_MINUTES | SUM_IN_HOURS
---------------------------------------
1505 | 25
select Sum(DATEDIFF(Minute,date1,date2)) AS TIME from ABC_tbl
u have to calculate the date difference with DATEDIFF function then use SUM function to calculate your sum of time.
you can change Minute to Second-Hour-month etc..
Try this:
DECLARE
#MidnightTime TIME = '00:00:00.0000000',
#MidnightDateTime DATETIME2 = '0001-01-01 00:00:00.0000000';
SELECT SumOfTime = DATEADD(SECOND, SUM ( DATEDIFF(SECOND, #MidnightTime, x.Col1) ), #MidnightDateTime)
FROM (VALUES
(1, CONVERT(TIME, '10:10:10.0000001')),
(2, CONVERT(TIME, '00:00:05.0000002')),
(3, CONVERT(TIME, '23:59:59.0000003'))
) x(ID, Col1)
/*
SumOfTime
---------------------------
0001-01-02 10:10:14.0000000 = 1 day (!), 10 hours, 10 minutes, 14 seconds
*/
Note: instead of SECOND you could use another precision: MINUTE, HOUR or ... NANOSECOND (see section Arguments > datepart). Using a higher precision could leads to Arithmetic overflow errors (use CONVERT(BIGINT|NUMERIC(...,0), ...).
Note #2: because the precision is SECOND the result (SumOfTime) has 0000000 nanoseconds.

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.