Share via

How to get decimal hour value in datediff function?

Lora 200 Reputation points
2023-12-29T02:04:02.6133333+00:00

Here is the sample:

select datediff(hour,'2023-12-28 09:00:00', '2023-12-28 18:30:00') 

The output value is '9'. However, I need '9.5' which is 9 hours and 30 minutes.

Thanks in advance.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
{count} votes

Answer accepted by question author
  1. LiHongMSFT-4306 31,621 Reputation points
    2023-12-29T02:21:08.6166667+00:00

    Hi @Lora

    Refering from this doc:

    Return Value The int difference between the startdate and enddate, expressed in the boundary set by datepart.

    You could modify the datepart from hour to second and then divide by 3600.

    Like this: select cast(datediff(s,'2023-12-28 09:00:00', '2023-12-28 18:30:00') as float) / 3600

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 47,616 Reputation points
    2023-12-29T06:16:31.01+00:00

    However**, I need '9.5'**

    Then get the diff in minutes and divide by 60.

    select datediff(MINUTE,'2023-12-28 09:00:00', '2023-12-28 18:30:00') / 60.0
    
    
    0 comments No comments

  2. Vahid Ghafarpour 23,600 Reputation points Volunteer Moderator
    2023-12-29T02:20:54.1833333+00:00

    Thanks for posting your question in the Microsoft Q&A forum.
    I would get diff in minutes and cast the division to decimal as follows:

    SELECT    CAST(datediff(minute, '2023-12-28 09:00:00', '2023-12-28 18:30:00') AS decimal(5, 2)) / 60 AS hours_difference; 
    

    ** Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful **

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.