Time part of a DateTime Field in SQL

后端 未结 11 1646
小蘑菇
小蘑菇 2020-12-03 04:39

How would I be able to extract the time part of a DateTime field in SQL? For my project I have to return data that has a timestamp of 5pm of a DateTime field no matter what

相关标签:
11条回答
  • 2020-12-03 04:56

    select cast(getdate() as time(0))

    returns for example :- 15:19:43

    replace getdate() with the date time you want to extract just time from!

    0 讨论(0)
  • 2020-12-03 04:57

    In SQL Server if you need only the hh:mi, you can use:

    DECLARE @datetime datetime
    
    SELECT @datetime = GETDATE()
    
    SELECT RIGHT('0'+CAST(DATEPART(hour, @datetime) as varchar(2)),2) + ':' +
           RIGHT('0'+CAST(DATEPART(minute, @datetime)as varchar(2)),2)
    
    0 讨论(0)
  • 2020-12-03 05:01

    "For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."

    So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:

    SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
    
    0 讨论(0)
  • 2020-12-03 05:03

    If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:

    declare @dt datetime
    set @dt = '2012-09-10 08:25:53'
    
    select datepart(hour, @dt) -- returns 8
    

    In SQL Server 2008+ you can CAST() as time:

    declare @dt datetime
    set @dt = '2012-09-10 08:25:53'
    
    select CAST(@dt as time) -- returns 08:25:53
    
    0 讨论(0)
  • 2020-12-03 05:07

    This will return the time-Only

    For SQL Server:

    SELECT convert(varchar(8), getdate(), 108)
    

    Explanation:

    getDate() is giving current date and time.
    108 is formatting/giving us the required portion i.e time in this case.
    varchar(8) gives us the number of characters from that portion.
    Like:
    If you wrote varchar(7) there, it will give you 00:00:0
    If you wrote varchar(6) there, it will give you 00:00:
    If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion. SQLFiddle Demo

    For MySQL:

    SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
    

    SQLFiddle Demo

    0 讨论(0)
提交回复
热议问题