Well done! You can also use the DATEPART
function to extract parts of date and time data. The function looks like this:
SELECT
DATEPART(datepart, date)
The date argument is the field, string, or expression that you'll extract data from. The datepart argument specifies what information will be returned. With this one function, you can return all types of time and date parts, including year
, quarter
, month
, dayofyear
, day
, week
, weekday
, hour
, minute
, second
, millisecond
, and tzoffset
(time zone offset).
Many T-SQL functions use datepart specifiers as an argument, so it's good to get familiar with this concept.
The DATEPART
function allows you to get part of a date or time. It returns an integer. Let's try it out in a query:
SELECT
DATEPART(hour, ArrivalTime) AS Hour
FROM Route;
This will return only the hour of each flight's arrival time. For route PA2342
, the arrival time is 09:30:00
. In this case, DATEPART
returns the hour, 9
.
Note that the datepart (hour
) isn't written between single quotes. The reason is simple: it's an identifier. We can't put identifiers between single quotes.