Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Round the datetime to 15 minute

Tags:

mysql

I want to update the datetime round to 15 minutes in a MYSQL database table.

For Example:

If the dateTime is 2013-10-08 10:36:00, I want to convert it into 2013-10-08 10:30:00 Similarly,2013-10-08 10:22:00 to 2013-10-08 10:15:00

I have seen this answer but it converts datetime into seconds and return time only, I want date as well.

Thanks

like image 247
Ana Avatar asked Oct 10 '13 08:10

Ana


People also ask

How do I round a date in MySQL?

DATE_FORMAT: DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00") returns the date truncated down to the nearest hour (sets the minute and second parts to zero). MINUTE: MINUTE(the_date) gets the minute value of the date.

How do you round off minutes in SQL?

This will round up or down to the nearest 15 minutes. SELECT DATEADD(MINUTE, ROUND(DATEDIFF(MINUTE, 0, GETDATE()) / 15.0, 0) * 15, 0);

What is timestamp in MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

How do I get the current date in SQL Workbench?

MySQL CURDATE() Function The CURDATE() function returns the current date.


2 Answers

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))
like image 74
AL̲̳I Avatar answered Sep 18 '22 14:09

AL̲̳I


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

like image 44
Paul Maxwell Avatar answered Sep 20 '22 14:09

Paul Maxwell