DATE_TRUNC
Description
The DATE_TRUNC function is used to truncate timestamp data to a specific point in time according to the specified field. This function can truncate time to different levels such as year, quarter, month, week, day, hour, minute, second, millisecond, or microsecond based on different field parameters.
Parameter Description
- field (string type): Represents the time field to truncate, common fields include 'YEAR', 'QUARTER', 'MONTH', 'WEEK', 'DAY', 'HOUR', 'MINUTE', 'SECOND', 'MILLISECOND', and 'MICROSECOND'. Field names are case-insensitive.
- expr (date/timestamp_ltz/string type): Represents the time data to be truncated.
Return Type
timestamp type.
Example
- Truncate to the first day of the specified year (time part set to zero):
- Truncate to the first day of the specified quarter (time part set to zero):
- Truncate to the first day of the specified month (time part set to zero):
- Truncate to the Monday of the specified week (time part set to zero):
- Truncate to the specified date (set the time part to zero):
- Truncate to the specified hour (minute, second, and millisecond parts set to zero):
- Truncate to the specified minute (set the second and millisecond parts to zero):
- Truncate to the specified second (milliseconds set to zero):
Notes
- When the expr parameter is of string type, ensure the string format is correct, otherwise it may cause the function to fail.
- This function does not alter the original time data for truncation operations, it only returns the truncated time result.