MYSQL Round the datetime to 15 minute

The answer you have seen is quite useful, try this

SELECT SUBSTRING_INDEX(datetime_field, ' ', -1) AS old_time,SEC_TO_TIME((TIME_TO_SEC(datetime_field) DIV 900) * 900) AS rounded_time, datetime_field FROM yourtable

You can get time from the datetime_field as substring and replace it with the rounded time.

If you want to update the datetime you can reply it and update it with update function:

UPDATE yourtable SET `datetime_field` =  REPLACE(datetime_filed,SUBSTRING_INDEX(datetime_field, ' ', -1),SEC_TO_TIME((TIME_TO_SEC(datetime_field) DIV 900) * 900))

SELECT NOW() x,FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(NOW())/900)*900) y;
+---------------------+---------------------+
| x                   | y                   |
+---------------------+---------------------+
| 2013-10-10 09:50:20 | 2013-10-10 09:45:00 |
+---------------------+---------------------+

using unix_timestamp allows quite simpe arithmetic, change 15 in the code below to some other number if needed (such as 30)

select from_unixtime(round(unix_timestamp('2013-10-08 10:36:00')/(60*15))*(60*15)); 

= October, 08 2013 10:30:00+0000

select from_unixtime(round(unix_timestamp('2013-10-08 10:22:00')/(60*15))*(60*15)); 

= October, 08 2013 10:15:00+0000

see: http://forums.mysql.com/read.php?20,131939,201089#msg-201089

Tags:

Mysql