Difference in minutes from two time fields in MySQL

后端 未结 4 1205
执笔经年
执笔经年 2020-11-29 09:47

I set up my MySQL database with the field \'time\'

It is not HH:MM in the traditional sense, it is the time an event occurred, so an event with the value of 5:45 occ

相关标签:
4条回答
  • 2020-11-29 10:22

    For me this worked:

    TIMESTAMPDIFF(MINUTE, T0.created, T0.modified)
    

    Reference: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff

    0 讨论(0)
  • 2020-11-29 10:33

    I used UNIX_TIMESTAMP(event1)-UNIX_TIMESTAMP(event2), which gives you seconds between events. Divide it by 60.0 and you will get a decimal as per your requirement. This solution assumes, your columns are date-compatible values. It will work really fast if they are TIMESTAMPs.

    UPDATE: This solution only works with timestamp data types, not time datatypes as in original question.

    0 讨论(0)
  • 2020-11-29 10:44

    I needed similar. Two useful functions: TIME_TO_SEC and SUBTIME.

    e.g. if your time fields were normal HH:MM times, then

    SELECT (TIME_TO_SEC(end_time) - TIME_TO_SEC(start_time))/60 AS `minutes` 
    

    In your case, as I understand it, the times are backwards, ie. 12:00<6:00 so your end_time and start_time would need swapping.

    If you wanted the output in HH:MM:SS you could do

    SELECT SUBTIME(end_time, start_time)
    
    0 讨论(0)
  • 2020-11-29 10:49

    Just use

    TIMEDIFF(fromtime, totime):
    
    SELECT TIMEDIFF("12:25", "5:45");
    

    If you need a decimal, use TIME_TO_SEC()/3600 (it assumes you passed it seconds, but the format you're storing the times in is vague and SQL probably will interpret them as HH:MM - you can fix this with CONCAT("00:",MinuteSecondField) maybe?) - then you can use TIME_TO_SEC()/60, which is more correct)

    0 讨论(0)
提交回复
热议问题