How to get half hour if exist with mysql hour function - mysql

I want to get 8:30 hour instead of 8 from below query
HOUR(TIMEDIFF('2018-12-01 07:00:00','2018-12-01 15:30:00')
Mysql hour function only return number of hour not half hour

We can get the difference between two datetime values in SECOND units, using TimeStampDiff() function. Now, we can convert this into Time using Sec_To_time() function.
SELECT SEC_TO_TIME(TIMESTAMPDIFF(SECOND, '2018-12-01 07:00:00','2018-12-01 15:30:00'))
Result
| SEC_TO_TIME(TIMESTAMPDIFF(SECOND, '2018-12-01 07:00:00','2018-12-01 15:30:00')) |
| ------------------------------------------------------------------------------- |
| 08:30:00 |

You may call both HOUR and MINUTE, the latter to get the minute component:
SELECT
HOUR(TIMEDIFF('2018-12-01 07:00:00','2018-12-01 15:30:00')) +
MINUTE(TIMEDIFF('2018-12-01 07:00:00','2018-12-01 15:30:00')) / 60.0 AS hours
FROM yourTable;
This outputs 8.5 for the number of hours.
Another option would be to first convert both timestamps to UNIX timestamps in seconds since epoch. Then convert their difference back to hours:
SELECT
(UNIX_TIMESTAMP('2018-12-01 15:30:00') -
UNIX_TIMESTAMP('2018-12-01 07:00:00')) / 3600.0 AS hours
FROM yourTable;
Demo

Related

Storing a duration in mysql

I need to store durations such as the following in mysql:
- 30 seconds
- 20 minutes, 12 seconds
- 1 month
What would be the best way to store this, as the definition of a month can't be reduced, for example, to a number of seconds. My first thought was to store each increment separate, for example:
- num_seconds
- num_minutes
- num_hours
- num_days
- num_months
This could store the above, but I was hoping there was a more direct and less verbose way of doing this.
My first option would be to store duration as a number of seconds with datatype INT. This will make computation and comparison operations fast and clean. Also you can easily compute the duration between two datetime values, by substracting their Unix timestamp. When you need to display the values, you can use mysql sec_to_time function :
However if you are looking to manipulate big durations (months, years), this will not work. In that case I would fallback on a VARCHAR column with iso8601 duration format, like P3Y6M4DT12H30M5S for 3 years, 6 months, 4 days, 12 hours, 30 minutes and 5 seconds. It is a well known format that is supported by many applications (but will be more tedious to manipulate).
Store your intervals for years to months as an integer counting the number of months (12 months = 1 year) and your intervals for days to seconds as an integer of number of seconds.
You can then use the DATE_ADD function to figure out your dates. Here's a SQL Fiddle example showing storing intervals as months and seconds, and adding them to a fixed date:
MySQL 5.6 Schema Setup:
create table mytab (dt date);
insert into mytab values (date '2018-01-01');
create table intervals (months int, seconds int);
insert into intervals values (13, 3661), (-13, -3661);
Query 1:
select dt
, months
, seconds
, date_add(date_add(dt, interval months month)
, interval seconds second) result
from mytab cross join intervals
Results:
| dt | months | seconds | result |
|------------|--------|---------|----------------------|
| 2018-01-01 | 13 | 3661 | 2019-02-01T01:01:01Z |
| 2018-01-01 | -13 | -3661 | 2016-11-30T22:58:59Z |

MYSQL Calculate date difference in digital time format

In one of the table I have 2 columns name date1 and date2 having datetime data type
I am calculating difference between these two dates using timediff(date2,date1). Now suppose
date1=2018-04-05 13:10:00
date2=2018-04-05 14:40:00
then the difference between these two dates will be 01:30:00
MY MAIN QUESTION IS how to convert this H:i:s time to digital time format like 01:30:00=1.5 or 01:45:00=1.75?
Use time_to_sec to convert to seconds. Then divide by 3600 (60 seconds per minute; 60 minutes per hour) to get to hours:
select time_to_sec(timediff(timestamp '2018-04-05 14:40:00',
timestamp '2018-04-05 13:10:00')) / 60 / 60;
By the way, you can also use timestampdiff instead of timediff to get seconds right away:
select timestampdiff(second, timestamp '2018-04-05 13:10:00',
timestamp '2018-04-05 14:40:00') / 3600;
select hour(timediff(date1, date2)) + minute(timediff(date1, date2))/60 + second(timediff(date1, date2))/60

MySQL: How to convert seconds to mm:ss format?

I want to convert seconds to minute : seconds format in sql select statement.
At the moment I am using:
SELECT SEC_TO_TIME(duration) from messages;
It works perfectly but it gives me this format of time: hh:mm:ss
but I need mm:ss
Is it possible to convert seconds into mm:ss format using sql query?
If the value is less than an hour, then just do:
SELECT RIGHT(SEC_TO_TIME(duration), 5) from messages;
If you might go over an hour, then do the arithmetic:
SELECT CONCAT_WS(':', FLOOR(SEC_TO_TIME(duration) / 60),
SEC_TO_TIME(duration) % 60)
I recently had a similar project where I needed to convert stored seconds to m:ss format. No matter the amount, there needed to be at least one digit representing minutes and two digits representing seconds. The hours placeholder was forbidden, so the minutes value could acceptably go beyond 59 and also contain more than 2 digits. The minute value must not be zero-padded.
This is what I used: (SQLFiddle Demo)
CONCAT(FLOOR(seconds/60), ':', LPAD(MOD(seconds,60), 2, 0)) AS `m:ss`
aka
CONCAT(FLOOR(seconds/60), ':', LPAD(seconds%60, 2, 0)) AS `m:ss`
seconds | m:ss
-----------------
0 | 0:00
1 | 0:01
10 | 0:10
60 | 1:00
61 | 1:01
71 | 1:11
3599 | 59:59
3600 | 60:00
5999 | 99:59
6000 | 100:00
TIME_FORMAT(SEC_TO_TIME(seconds),'%i:%s') was unsuitable because the project specifications did not want the minute portion to be zero-padded. Here is a good post relating to this technique.
There is no single-digit minute option in TIME_FORMAT() or DATE_FORMAT().
If you are using MySQL 8.0+ you can use REGEXP_REPLACE like this to achieve a variable length string similar mickmackusa's answer:
REGEXP_REPLACE(SEC_TO_TIME(duration), '^(0|:)+', '')

Date Difference in MySQL in Minutes

I need to find the time difference in Hours for the following Dates in MySQL - Can i use Datediff functions?
2014-01-01 07:27:21 and 2014-02-01 11:29:00
I tried using DATEDIFF(MINUTE,'2014-01-01 07:27:21','2014-01-01 11:29:00') but apparently MySQL is giving an error.
Time difference in minutes:
SELECT ROUND(TIME_TO_SEC(timediff(date1,date2))/60) AS diff
Example:
SELECT ROUND(TIME_TO_SEC(timediff('2014-01-01 11:29:00','2014-01-01 07:27:21'))/60) AS diff
Result:
242
Time difference in hours:
SELECT ROUND(TIME_TO_SEC(timediff(date1,date2))/60/60) AS diff
if you need number of hours with fractions then remove ROUND.

Interval from difference of two times in MySQL

I have a MySQL query that uses two different timestamps that can be perceived as an interval of time. I need to implement an extra 25-30% of the difference. For example, if the difference between the times is 30 minutes, I need to request an additional 5 minutes before and 5 minutes after.. Is there a way to not only get the difference between the two time stamps, but then calculate this 'percentage' of time to acquire the appropriate interval, all within one statement?
Something like the following, where x is the calculated value.
..
DATE_FORMAT(timestamp1 - INTERVAL x MINUTE,'%m/%d/%Y %r') AS 'Start',
DATE_FORMAT(timestamp2 + INTERVAL x MINUTE,'%m/%d/%Y %r') AS 'End',
..
You have a start timestamp and an end timestamp in the database. You want to add an additional percentage of time to these values, based on the time span between them. In other words, you can't add or subtract any amount of time without knowing the difference between the two.
So, first you must figure out the time span. I'm going to use minutes as the unit, but use whatever works best for your needs:
SELECT
#new_span := TIMESTAMPDIFF(MINUTE, timestamp1, timestamp2) * 1.25 new_span,
DATE_SUB(timestamp1, INTERVAL (#new_span*60)/2 SECOND) AS new_start,
DATE_ADD(timestamp2, INTERVAL (#new_span*60)/2 SECOND) AS new_end,
TIMESTAMPDIFF(MINUTE, timestamp1, timestamp2) old_span,
timestamp1 AS previous_start,
timestamp2 AS previous_end
FROM table;
So this query stores the difference between the two times plus 25% as a variable named new_span. The new_start and new_end fields use the variable (converted to seconds and divided in half) to modify the original start/end times. I'm also selecting old_span and the original start/end times, for comparison.
Here is sample output:
new_span new_start new_end old_span previous_start previous_end
1.25 2011-08-11 15:53:22 2011-08-11 15:55:38 1 2011-08-11 15:54:00 2011-08-11 15:55:00
1350.00 2011-08-09 00:45:00 2011-08-10 17:15:00 1080 2011-08-09 12:00:00 2011-08-10 06:00:00