How to round minute in SQL (Databricks) or PostgreSQL to nearest hour
To round minute to nearest hour you have to use: date_trunc('hour', 'YOUR DATE_TIME' + interval '30 minute')
DATE_TRUNC function rounds to the hour that appears in the string, so if we add +30 minutes when you have a HH:30+, this should round to next hour and when you have HH:-30 this will round to the hour that appears in your string.
So if hour is: '2022-11-21 00:05:00', the new time will be: '2022-11-21 00:00:00'
But if hour is: '2022-11-21 00:55:00', the new time will be: '2022-11-21 01:00:00'
Between 0 and 30 minutes: Rounds to the same hour in your date_time Between 31 and 59 minutes: Rounds to the next hour based on your date_time
DATE_TRUNC function rounds to the hour that appears in the string, so if we add +30 minutes when you have a HH:30+, this should round to next hour and when you have HH:-30 this will round to the hour that appears in your string.
So if hour is: '2022-11-21 00:05:00', the new time will be: '2022-11-21 00:00:00'
But if hour is: '2022-11-21 00:55:00', the new time will be: '2022-11-21 01:00:00'
Between 0 and 30 minutes: Rounds to the same hour in your date_time Between 31 and 59 minutes: Rounds to the next hour based on your date_time
Comments
Post a Comment