Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
mysql 5.6 round datetime to nearest minute

I am trying to round a millisecond precision DATETIME, i.e. DATETIME(3) to the nearest minute. For example:

2020-07-27 17:33:59.954 => 2020-07-27 17:34:00.000
2020-07-27 17:42:58.799 => 2020-07-27 17:42:59.000
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

mysql> select now(3), from_unixtime(floor((unix_timestamp(now(3))+30)/60)*60) as nearest_minute;
+-------------------------+---------------------+
| now(3)                  | nearest_minute      |
+-------------------------+---------------------+
| 2020-07-31 18:46:22.518 | 2020-07-31 18:46:00 |
+-------------------------+---------------------+
over 4 years ago · Santiago Trujillo Report

0

Simply use CAST it as DATETIME

CREATE TABLE Table1
    (`dt` datetime(6))
;
    
INSERT INTO Table1
    (`dt`)
VALUES
    ('2020-07-27 17:33:59.954'),
    ('2020-07-27 17:42:58.799')
;
SELECT `dt` ,CAST(`dt` AS DATETIME)  FROM Table1
dt                         | CAST(`dt` AS DATETIME)
:------------------------- | :---------------------
2020-07-27 17:33:59.954000 | 2020-07-27 17:34:00   
2020-07-27 17:42:58.799000 | 2020-07-27 17:42:59   

db<>fiddle here

over 4 years ago · Santiago Trujillo Report

0

Here is the rather unsatisfying solution I came up with:

CREATE FUNCTION timestamp_to_nearest_minute (t DATETIME)
RETURNS DATETIME DETERMINISTIC
RETURN 
    CASE 
    WHEN CAST(EXTRACT(MICROSECOND FROM t) AS DECIMAL(11,3)) / 1000.0 < 500
        THEN 
            DATE_SUB(t, INTERVAL CAST(EXTRACT(MICROSECOND FROM t) AS DECIMAL(11,3)) MICROSECOND)
        ELSE
            DATE_ADD(t, INTERVAL 1000000.0 - CAST(EXTRACT(MICROSECOND FROM t) AS DECIMAL(11,3)) MICROSECOND)
    END
;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!