Extract time from datetime efficiently (as decimal or datetime) - sql

I have been able to find a lot of information for getting a string representation of just the time from a datetime column like this one.
I need to get the time part out of a datetime in a way that I can do some math on it like adding it to another datetime. So a string representation of the time wont help me.
However I've only found one example that will extract the time as a numeric type value. I.e:
SELECT CAST(GETDATE() AS FLOAT) - FLOOR(CAST(GETDATE() AS FLOAT))
This method requires two casts though and I have to run this on over 10,000 rows. Is there anything similar to the dateadd method for extracting the date part from a datetime column i.e.:
select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
that I can use to get just the time out of a datetime column and return it as a decimal or datetime? Perhaps a solution that uses less casting?
I am using SQL Server 2000.

To get a datetime:
SELECT GetDate() - DateDiff(day, 0, GetDate());
-- returns the time with zero as the datetime part (1900-01-01).
And to get a number representing the time:
SELECT DateDiff(millisecond, DateDiff(day, 0, GetDate()), GetDate());
-- time since midnight in milliseconds, use as you wish
If you really want a string, then:
SELECT Convert(varchar(8), GetDate(), 108); -- 'hh:mm:ss'
SELECT Convert(varchar(12), GetDate(), 114); -- 'hh:mm:ss.nnn' where nnn is milliseconds

One way You can get the time in seconds is with:
select cast(datediff(second, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), getdate())/(60*60*24.0) as datetime)
This calculates the time in seconds and then converts back to a datetime.
To get it as a decimal:
select datediff(second, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0), getdate())/(60*60*24.0)
Or use "ms" if you prefer millisecond precision.
Or, you can use the more readable:
select datepart(hh, getdate())/24.0+datepart(mm, getdate())/(24*60.0)+
datepart(ss, getdate())/(24*60*60.0)

Related

SQL View: Optimizing real-time data

I am having an issue with a query a while to run.
The scenario is this: I have an efficiency metric being populated within a view taking in inputs from another view. This calculation utilizes GETUTCDATE()and I am just adjusting for my time zone. I am calculating efficiency by way of using a "BuildTime" column value versus how much time has passed since 7:00 AM of the current day (e.g. if 120min have passed since 7AM and "BuildTime" equals 120min, the efficiency is 100%. I am also using a CASE function to only calculate the current passing time between operating hours (7AM - 3:30PM)
Attached below is the code:
SELECT
md.Operator,
CASE
WHEN DATEADD(HOUR, -6, GETUTCDATE()) > CONVERT(DATETIME, CONVERT(DATE, DATEADD(HOUR, -6, GETUTCDATE()))) + '7:00' AND GETDATE() < CONVERT(DATETIME, CONVERT(DATE, DATEADD(HOUR, -6, GETUTCDATE()))) + '15:30' THEN
(SUM(isNull(md.TotalTime, 0)) + SUM(isNull(md.DelTime, 0))) * 1.0 / DATEDIFF(MINUTE, CONVERT(DATETIME, CONVERT(DATE, DATEADD(HOUR, -6, GETUTCDATE()))) + '7:00' , DATEADD(HOUR, -6, GETUTCDATE())) * 100.0
ELSE (SUM(isNull(md.TotalTime, 0)) + SUM(isNull(md.DelTime, 0))) / 435 * 100.0
END
AS OpEfficiency
FROM [Booms MES Master Data] as md
WHERE md.[Date] = CONVERT(varchar(50), DATEADD(HOUR, -6, GETUTCDATE()), 101)
GROUP BY md.Operator
As of now, this code takes several seconds to run. I'm wondering where the problem lays within the code? Am I converting too many statements or is it an issue with a nested if function?
If you have a very large dataset, as a rule of thumb, start with your fixed value first and limit your conversion to the minimal amount of characters. In this case varchar(10) since a 101 format date only has 10 character ( '12/12/1234' ).
WHERE CONVERT(varchar(10), DATEADD(HOUR, -6, GETUTCDATE()), 101) = md.[Date]
You can use Microsoft's Analyze an Actual Execution Plan to detect the further issues.
https://learn.microsoft.com/en-us/sql/relational-databases/performance/analyze-an-actual-execution-plan
Also consider converting to dates instead of varchar, if you code is running on sql server 2012+. Dates are stored as two integer in sql server. It is far easier for sql to find a specific number once sorted than searching for a string sorted as mm/dd/yy if you have multiple years of data.
WHERE CONVERT(date, DATEADD(HOUR, -6, GETUTCDATE())) = CONVERT(date,md.[Date])

How to only check the time on datetime fields but ignore the date?

I have a column that stores data in datetime format. I want to check for all instances where the time part of this column is not equal to 00:00:00:000 - the date does not matter.
Basically, if time() was a function, something like this:
SELECT *
FROM progen.DY
WHERE TIME(DY_DATE) <> '00:00:00:000'
How do I go about doing this?
You only need a minor tweak on what you already have.
SELECT *
FROM progen.DY
WHERE TIME(DY_DATE) <> '00:00:00:000'
Use CONVERT to change your DATETIME to a TIME.
SELECT *
FROM progen.DY
WHERE CONVERT(TIME, DY_DATE) <> '00:00:00:000'
Another way is to convert it to different datatype, eg
SELECT *
FROM progen.DY
WHERE CAST(DY_DATE as float) - CAST(DY_DATE as int) > 0
SQLFiddle Demo
I do this all the time when trying to see if a table's column should be turned into a date instead of a datetime, which is really the answer.
select *
from progen.dy
where cast(dy_date as Date) <> dy_date
the cast removes the time and datetime has higher precedence, so when compared, if the are unequal then it has a time value. Same thing could be done with a cast to time, with a bit of different syntax.
Use DATEDIFF and DATEADD to instead get the date part of the datetime. Compare the column against the date only, and it will return those rows that have a non-zero time.
The way this works is that we first calculate the difference (in days) between the epoch and the value. We add that number to the epoch to create a new datetime. Since the result of DATEDIFF is an integer, any time component gets rounded off.
SELECT *
FROM Table
WHERE DateColumn <> DATEADD(d, DATEDIFF(d, 0, DateColumn), 0)
The time function could then be implemented by the following, not that I recommend it for this specific scenario:
SELECT DATEDIFF(minute, DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), DateColumn) as MinutesIntoDay,
-- or, if you require higher precision
DATEDIFF(second, DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), DateColumn) as MinutesIntoDay
FROM Table
Edit: As mentioned in other answers, you can cast to DATE to achieve the same effect as DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), which cleans up nicely. However, DATE was only added in SQL Server 2008, whereas the formula has compatibility back to at least SQL 2000. So if you need the backwards compatibility or are dealing with SQL CE, casting to DATE is unavailable.
SELECT *
FROM progen.DY
WHERE CONVERT(TIME, DY_DATE - CONVERT(DATE, DY_DATE)) > '00:00'

Converting Milliseconds to Days, hours, minutes and seconds

i have a bigint field in Microsoft SQL Server 2008R2 filled with ticks (A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.)
http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
and i need to convert the sum of all records to Days:Hours:Minutes:Seconds:Milliseconds.
it works for a single record:
SELECT CONVERT(TIME, DATEADD(ms, duration/10000, 0)) FROM tblMediaFileProperties WHERE FileId = '6C0A849D-95B4-4755-A923-B9DD8F1AF23E'
but if a sum it up to all records using:
SELECT CONVERT(TIME, DATEADD(ms, SUM(duration/10000), 0)) FROM tblMediaFileProperties
i get a:
Arithmetic overflow error converting expression to data type int.
i know the overflow comes from the CONVERT to Data Type TIME Function...
help's appreciated, thanks!
It's too big for DATEADD which only accepts an int.
Break it into two parts: seconds, then milliseconds.
SELECT CONVERT(TIME,
DATEADD(ms, SUM(duration/10000 % 1000),
DATEADD(ss, SUM(duration/10000000), 0)))
FROM tblMediaFileProperties
And if your total duration goes above 1 day, you can use this to get the days and hr:min:sec:ms separately. It's a matter of cast and string concat if you actually want the result in textual form.
declare #duration bigint
set #duration = 1230000000
SELECT #duration/10000/1000/60/60/24 DAYS,
CONVERT(TIME,
DATEADD(ms, SUM(#duration/10000 % 1000),
DATEADD(ss, SUM(#duration/10000000), 0))) HR_MIN_SEC

SQL HELP... CONVERT(int, CONVERT(datetime, FLOOR(CONVERT(float, getdate())))

I am having a problem adjusting this part of my SQL statement:
HAVING dbo.BOOKINGS.BOOKED = CONVERT(int, CONVERT(datetime,
FLOOR(CONVERT(float, GETDATE()))) + 2)
Normally, the page that uses this statement just lists the amount of sales for today, I want to switch the GETDATE() to a date that I declare. I tried all different formats and none have worked
Use the DATEADD/DATEDIFF method of setting the time portion to midnight of the current date - it's the fastest means, and casting to FLOAT can be unreliable:
HAVING BOOKINGS.dbo.BOOKED = CONVERT(INT, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))+2
Then, you can set your own date easily if you use a variable (#var in this example, within a stored procedure or function):
DECLARE #var DATETIME
SELECT ...
HAVING BOOKINGS.dbo.BOOKED = CONVERT(INT, DATEADD(dd, DATEDIFF(dd, 0, #var), 0))+2
This assumes #var is a DATETIME data type. Otherwise, you'll need to use a date format SQL Server will implicitly convert to a DATETIME -- or use CAST/CONVERT to explicitly convert the value.
if you want you to give your own date you could do this instead of getdate() which gives current system timestamp.
Cast('2010-11-04 13:28:00.000' as datetime)
How about
declare #myDate as datetime
set #myDate = '11/2/2010'
. . .
HAVING dbo.BOOKINGS.BOOKED = CONVERT(int, CONVERT(datetime,
FLOOR(CONVERT(float, #myDate ))) + 2)
That should do it, and it should automatically do the type conversion on your date string used in the set statement, or you could just pass in a datetime parameter if this is in a stored procedure.

Best way to check for current date in where clause of sql query

I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using:
SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
WHERE
DateDiff(d, Received, GETDATE()) = 0
Edit: As lined out in the comments to this answer, that's not an ideal solution. Check the other answers in this thread, too.
If you just want to find all the records where the Received Date is today, and there are records with future Received dates, then what you're doing is (very very slightly) wrong... Because the Between operator allows values that are equal to the ending boundary, so you could get records with Received date = to midnight tomorrow...
If there is no need to use an index on Received, then all you need to do is check that the date diff with the current datetime is 0...
Where DateDiff(day, received, getdate()) = 0
This predicate is of course not SARGable so it cannot use an index...
If this is an issue for this query then, assuming you cannot have Received dates in the future, I would use this instead...
Where Received >= DateAdd(day, DateDiff(Day, 0, getDate()), 0)
If Received dates can be in the future, then you are probably as close to the most efficient as you can be... (Except change the Between to a >= AND < )
If you want performance, you want a direct hit on the index, without any CPU etc per row; as such, I would calculate the range first, and then use a simple WHERE query. I don't know what db you are using, but in SQL Server, the following works:
// ... where #When is the date-and-time we have (perhaps from GETDATE())
DECLARE #DayStart datetime, #DayEnd datetime
SET #DayStart = CAST(FLOOR(CAST(#When as float)) as datetime) -- get day only
SET #DayEnd = DATEADD(d, 1, #DayStart)
SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received >= #DayStart AND Received < #DayEnd)
that's pretty much the best way to do it.
you could put the DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0) and DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1) into variables and use those instead but i don't think that this will improve performance.
I'm not sure how you're defining "best" but that will work fine.
However, if this query is something you're going to run repeatedly you should get rid of the get_date() function and just stick a literal date value in there via whatever programming language you're running this in. Despite their output changing only once every 24 hours, get_date(), current_date(), etc. are non-deterministic functions, which means that your RDMS will probably invalidate the query as a candidate for storing in its query cache if it has one.
How 'bout
WHERE
DATEDIFF(d, Received, GETDATE()) = 0
I would normally use the solution suggested by Tomalak, but if you are really desperate for performance the best option could be to add an extra indexed field ReceivedDataPartOnly - which would store data without the time part and then use the query
declare #today as datetime
set #today = datediff(d, 0, getdate())
select
count(job) as jobs
from
dbo.job
where
received_DatePartOnly = #today
Compare two dates after converting into same format like below.
where CONVERT(varchar, createddate, 1) = CONVERT(varchar, getdate(), 1);