How do you use the DATEPART function to extract specific parts of a datetime value?
Posted by RoseHrs
Last Updated: June 17, 2024
The DATEPART function is commonly used in SQL to extract specific components (parts) of a datetime value. This function is available in various database systems, such as SQL Server and others. Here's how to use the DATEPART function in SQL Server, along with examples for extracting different parts of a datetime:
Syntax
DATEPART(datepart, date)
- datepart: This argument specifies which part of the date you want to extract. It can be a year, quarter, month, day, etc. - date: This is the datetime expression from which you want to extract the specified part.
Common Date Parts
Here are some common datepart values you can use: - year or yy or yyyy: Extracts the year. - quarter or qq or q: Extracts the quarter (1-4). - month or mm or m: Extracts the month (1-12). - day or dd or d: Extracts the day of the month (1-31). - week or wk or ww: Extracts the week number (1-53). - hour or hh: Extracts the hour (0-23). - minute or mi or n: Extracts the minute (0-59). - second or ss or s: Extracts the second (0-59).
Examples
1. Extract Year:
SELECT DATEPART(year, GETDATE()) AS CurrentYear;
2. Extract Month:
SELECT DATEPART(month, GETDATE()) AS CurrentMonth;
3. Extract Day:
SELECT DATEPART(day, GETDATE()) AS CurrentDay;
4. Extract Hour:
SELECT DATEPART(hour, GETDATE()) AS CurrentHour;
5. Extract Week:
SELECT DATEPART(week, GETDATE()) AS CurrentWeek;
Example with a Specific Date
If you want to extract parts from a specific date (for example, '2023-10-15 12:30:45'), you can do it like this:
SELECT 
    DATEPART(year, '2023-10-15 12:30:45') AS Year,
    DATEPART(month, '2023-10-15 12:30:45') AS Month,
    DATEPART(day, '2023-10-15 12:30:45') AS Day,
    DATEPART(hour, '2023-10-15 12:30:45') AS Hour,
    DATEPART(minute, '2023-10-15 12:30:45') AS Minute,
    DATEPART(second, '2023-10-15 12:30:45') AS Second;
Conclusion
The DATEPART function is a powerful tool for working with date and time data in SQL. It allows you to easily extract individual components from datetime values for reporting, analysis, or further calculations. Make sure to use the appropriate datepart according to your requirements!
Related Content