Convert this format of time to seconds - sql

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)

Related

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 Between HubSpot Unix Timestamp and SQL DateTime

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')
)

How to convert a single Oracle datetime into minutes?

I wish to convert a single Oracle datetime value to minutes.
As an example, I need to convert the current date/time alone into minutes, i.e.:
select (sysdate)*24*60 from dual
but this is giving me an error.
I basically need to perform a check to see that a certain operation cannot be performed until 30 minutes before a particular date/start time, that exists in the database.
So if the Start Time in the DB is:
24/04/2014 22:00:00 and the current date/time (SYSDATE) is 24/04/2014 21:29:59,
then operation CANNOT be performed but if the current date/time (SYSDATE) is:
24/04/2014 21:30:00,
then operation CAN be performed.
You probably want something like
startTime - interval '30' minute >= sysdate
or
startTime >= sysdate + interval '30' minute
You could also subtract the two date values which gives you the number of days between them and multiply
(startTime - sysdate)*24*60 >= 30
but I generally find the interval notation clearer and easier to read. It's also easier to structure in a way that allows you to use indexes on columns like startTime.
select (sysdate - trunc(sysdate)) *24 *60 from dual
You seem to want to know if the seconds component of sysdate is 0. So, test for that:
where extract(second from sysdate) = 0
Oops, I misread the question. You just need a difference of 30 minutes. That is also easy:
where starttime <= sysdate + 30/(24*60)
When you add an integer to a datetime, it is interpreted as a number of days. The expression 30/(24*60) is an expression for half an hour measured in days.

how to add 2 varchar columns in sql

I have timediff field as varchar
I want to find sum of this field but it gives error as
"Syntax error converting the varchar value '02:00' to a column of data type int."
My timediff is like
02:00
03:00
04:00
i want to add and should display 9 in sql
please help me
thanks for helping me
You can't use SUM on a varchar column. Take a look at the documentation here.
You haven't given us much information about what you are storing or how you want it summed, but your best bet might be to parse out the number before your colon, convert it to an int and sum that.
Good luck!
If you are talking about MS SQL
You could do something like this
first convert your hour representation to minutes by this
select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))
Then use that minutes representation to perform addition like this
select
DATEADD(
minute,
(select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))),
getdate())
If your final goal is to get sum of all datadiff records in hh:mm then first store datediff in minutes instead of hh:mm which you asked here.
How to store DateDiff in minutes:
SELECT DATEDIFF(second,CAST(<timepart> AS DATETIME)
, CAST(<timepart> AS DATETIME))/60.0 AS MIN_DIFF;
For example
SELECT DATEDIFF(second,CAST('10:00 AM' AS DATETIME)
, CAST('11:15 AM' AS DATETIME))/60.0 AS MIN_DIFF;
How to do sum of all minutes in hh:mm
SELECT CAST((<total minutes> / 60) AS VARCHAR(8)) + ':'
+ CAST((<total minutes> % 60) AS VARCHAR(2))
For example
SELECT CAST((390 / 60) AS VARCHAR(8)) + ':'
+ CAST((390 % 60) AS VARCHAR(2))
See this fiddle for all your answers.

How to get Date diffrence in hh:mm format In Select Query Sql 2005

I am trying to get the the result of in time and out time from dates
but it returns only hours using following select Query as follows
SELECT DATEDIFF(Hh,InTime,OutTime) as Diff_time from EmpLogTable
and i need result in HH:MM
Suppose my in time is 11 am and out is 5.49pm so o/p would be 6.49 but
using above select query i am getting o/p as 7 only
if any body has a solution then please let me know
Thanking you in Advance
Umesh Rakhe
The DATEDIFF function returns an INT so it will not work as you like, your best bet is to subtract InTime from OutTime or use DATEDIFF with minutes (n) instead.
you should probably do UI formatting on the client, not the database
you can use diff = datediff(mi, intime, outtime) to get the difference in minutes
then divide diff by 60 to get the hours
and take the modulus diff % 60 to get the remaining minutes
then turn into strings and you're good to go
SELECT Outime - InTime as Diff_time from EmpLogTable
DATEDIFF measures day, hour etc boundaries: you're asking for a true date/time difference. In this case, I'd simply subtract the values rather than using a complex nested DATEDIFF. Or do it in the client.
If you have a interval > 24 hours though, then you'd need a nested DATEDIFF to get 25 hours: my answer would give one day and one hour.
The hh:nn:ss format can be done via CONVERT with style 108, but again I'd do this in the client