SQL Server DATEPART() Function

The DATEPART() function in SQL Server extracts a specific part (year, month, day, hour, minute, second, etc.) from a date or datetime value. It's a very useful function for working with dates and times.



DATEPART(): Definition and Usage

DATEPART() allows you to isolate individual components of a date or time. This is extremely helpful for filtering, grouping, or calculating based on specific parts of a date. The returned value is always an integer.

Syntax

Syntax

DATEPART(interval, date)
      

Parameter Values

Parameter Description
interval The part of the date to extract. Options:
  • year, yyyy, yy: Year
  • quarter, qq, q: Quarter
  • month, mm, m: Month
  • dayofyear, dy, y: Day of the year
  • day, dd, d: Day of the month
  • week, ww, wk: Week
  • weekday, dw, w: Weekday
  • hour, hh: Hour
  • minute, mi, n: Minute
  • second, ss, s: Second
  • millisecond, ms: Millisecond
  • microsecond, mcs: Microsecond
  • nanosecond, ns: Nanosecond
  • tzoffset, tz: Timezone offset
  • iso_week, isowk, isoww: ISO week
This is required.
date The date or datetime value. Can be: date, datetime, datetimeoffset, datetime2, smalldatetime, or time. This is required.

Examples

Extracting the Year

Getting the year from the date '2017/08/25'.

Syntax

SELECT DATEPART(year, '2017/08/25') AS DatePartInt;
      
Output

2017
      

Extracting the Year (alternative syntax)

Another way to get the year.

Syntax

SELECT DATEPART(yy, '2017/08/25') AS DatePartInt;
      
Output

2017
      

Extracting the Month

Getting the month from the date.

Syntax

SELECT DATEPART(month, '2017/08/25') AS DatePartInt;
      
Output

8
      

Extracting the Hour

Getting the hour from a datetime value.

Syntax

SELECT DATEPART(hour, '2017/08/25 08:36') AS DatePartInt;
      
Output

8
      

Extracting the Minute

Getting the minute from a datetime value.

Syntax

SELECT DATEPART(minute, '2017/08/25 08:36') AS DatePartInt;
      
Output

36