如何在 MySQL 中对 DateTime 进行四舍五入?
我想以 5 分钟的分辨率离散化日期时间。我是用C#做的,但是下面的代码如何转换成MySQL呢?
DateTime Floor(DateTime dateTime, TimeSpan resolution)
{
return new DateTime
(
timeSpan.Ticks *
(long) Math.Floor
(
((double)dateTime.Ticks) /
((double)resolution.Ticks)
)
);
}
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 resolution)
{
return new DateTime
(
timeSpan.Ticks *
(long) Math.Floor
(
((double)dateTime.Ticks) /
((double)resolution.Ticks)
)
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当您使用日期时间数据类型时,这有点令人讨厌;存储函数的一个很好的候选者。
使用 UNIXTIME 时间戳会更容易,但仅限于 1970 - 2038 日期范围。
祝你好运。
It's a little nasty when you do it with datetime data types; a nice candidate for a stored function.
It's easier when you use UNIXTIME timestamps but that's limited to a 1970 - 2038 date range.
Good luck.
您可以将两个5替换为其他值
you can replace the two 5s with other values
您看过 MySQL 中的 CAST 功能吗?
Have you had a look at the CAST functionality in MySQL?
您可以查看此处。此示例是四舍五入到最接近的 X 分钟的一般情况,并用 T-SQL 编写,但两种情况下的逻辑和大多数函数都是相同的。
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.
另一种选择:
要获取最近小时:
您可以使用任意日期代替
CURDATE()
,例如'2000-01-01'
>不确定如果系统日期在两次调用函数之间发生变化,使用 CURDATE() 是否会出现问题,不知道 Mysql 是否会同时调用两者。
将 60 更改为 15 将获得最接近的 15 分钟间隔,使用 SECOND 您可以获得最接近的所需秒间隔,依此类推。
要获取前一小时,请使用
TRUNCATE()
或FLOOR()而不是
ROUND()
。希望这有帮助。
Another alternative:
to get the nearest hour:
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()
orFLOOR()
instead ofROUND()
.Hope this helps.
这是基于此线程的解决方案的另一种变体。
与使用
FROM_UNIXTIME
的解决方案不同,此解决方案将给出夏令时 (DST) 转换范围内的日期时间的预期值。 (例如比较 2012-11-03 2:14:00)编辑 - 然而,经过一些快速基准测试后,Ollie 的第一个解决方案的执行速度似乎比这更快。但我仍然建议不要使用 FROM_UNIXTIME 方法。
Here is another variation based on a solution from this thread.
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.