How to round a DateTime in MySQL?
I want to discretize the DateTime with the resolution of 5 minutes. I did it in C#, but how to convert the following code to MySQL?
DateTime Floor(DateTime dateTime, TimeSpan resolut开发者_JAVA百科ion)
{
return new DateTime
(
timeSpan.Ticks *
(long) Math.Floor
(
((double)dateTime.Ticks) /
((double)resolution.Ticks)
)
);
}
It's a little nasty when you do it with datetime data types; a nice candidate for a stored function.
DATE_SUB(DATE_SUB(time, INTERVAL MOD(MINUTE(time),5) MINUTE ),
INTERVAL SECOND(time) SECOND)
It's easier when you use UNIXTIME timestamps but that's limited to a 1970 - 2038 date range.
FROM_UNIXTIME(UNIX_TIMESTAMP(time) - MOD(UNIX_TIMESTAMP(time),300))
Good luck.
from_unixtime(floor(unix_timestamp('2006-10-10 14:26:01')/(60*5))*(60*5))
+---------------------------------------------------------------------------+
| from_unixtime(floor(unix_timestamp('2006-10-10 14:26:01')/(60*5))*(60*5)) |
+---------------------------------------------------------------------------+
| 2006-10-10 14:25:00 |
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)
you can replace the two 5s with other values
You can look here. This example is a general case for rounding to the nearest X minutes, and is written in T-SQL, but the logic and the majority of the functions will be the same in both cases.
Another alternative:
to get the nearest hour:
TIMESTAMPADD(MINUTE,
ROUND(TIMESTAMPDIFF(MINUTE,CURDATE(),timestamp_column_name)/60)*60,
CURDATE())
Instead of CURDATE()
you can use an arbitrary date, for example '2000-01-01'
Not sure if there could be problems using CURDATE()
if the system date changes between the two calls to the function, don't know if Mysql would call both at the same time.
changing 60 by 15 would get the nearest 15 minutes interval, using SECOND you can get the nearest desired second interval, etc.
To get the previous hour use TRUNCATE()
or FLOOR()
instead of ROUND()
.
Hope this helps.
Have you had a look at the CAST functionality in MySQL?
- MySQL Cast
- Cast Functions and Operators
Here is another variation based on a solution from this thread.
SELECT DATE_ADD(
DATE_FORMAT(time, "%Y-%m-%d %H:00:00"),
INTERVAL FLOOR(MINUTE(time)/5)*5 MINUTE
);
This solution, unlike ones that use FROM_UNIXTIME
, will give the expected value for datetimes that fall within daylight saving time (DST) transitions. (Compare for example 2012-11-03 2:14:00)
Edit - After some quick benchmarking, however, Ollie's first solution appears to perform faster than this. But I still recommend against the FROM_UNIXTIME method.
精彩评论