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|:)+', '')
Related
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 |
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
I use the TIME field quite frequently to store a second-accurate duration. However, how would I store something like:
4 hours, 3 minutes, 1.1828999 second
I would prefer not to store it as a float or decimal, but in a way that is clear it's a time duration. How should I do this?
Store it as a TIME(6) to get up to six digits of precision for fractional seconds. Time precision is a feature introduced in MySQL 5.6.
Storage of fractional seconds costs an extra 3 bytes per column. See https://dev.mysql.com/doc/refman/5.6/en/storage-requirements.html#data-types-storage-reqs-date-time for details.
Then you can format it as you select the value:
mysql> select current_time(6),
date_format(current_time(6), '%H hours, %i minutes, %s.%f seconds') as `formatted time`;
+-----------------+-----------------------------------------+
| current_time(6) | formatted time |
+-----------------+-----------------------------------------+
| 00:24:53.843700 | 00 hours, 24 minutes, 53.843700 seconds |
+-----------------+-----------------------------------------+
See DATE_FORMAT() for other formatting options.
For example, I have a time format: 1000
how do I convert into MySQL Time() 10:00:00
It can also be more complex, since some numbers are 3 digits long, for example:
900 into MySQL Time() 09:00:00
Let me know if this needs more explaining.
You just want to use str_to_date()
cast your into to a char so its a string and pad it with lpad to keep a leading 0 :)
SELECT STR_TO_DATE(LPAD(CAST(my_col AS CHAR(25)), 4, '0'), '%H') -- or %k
or you can just drop the cast since mysql will do the converting for you
SELECT STR_TO_DATE(LPAD(my_col, 4, '0'), '%k')
FIDDLE
Use CONVERT() -- (http://dev.mysql.com/doc/refman/5.7/en/charset-convert.html)
You'll have to pad it with zeros to show CONVERT() that it is in hours and not minutes.
Specific to your example:
> SELECT CONVERT(CONCAT('1000','00'), TIME) AS time1;
time1
10:00:00
or
> SELECT CONVERT(CONCAT(`fieldname`,'00'), TIME) AS time1 FROM `tablename`;
time1
10:00:00
Select cast(number*100 as time)
Explanation: as mysql documentation on time data type says:
MySQL interprets abbreviated values without colons using the assumption that the two rightmost digits represent seconds (that is, as elapsed time rather than as time of day). For example, you might think of '1112' and 1112 as meaning '11:12:00' (12 minutes after 11 o'clock), but MySQL interprets them as '00:11:12' (11 minutes, 12 seconds). Similarly, '12' and 12 are interpreted as '00:00:12'.
So, if you want to interpret 1000 as 10 hours and 0 minutes, you need to multiply your number by 100 an interpret it as a time expression.
I'm trying to switch from using UNIX timestamps to DATETIME columns in MySQL and am having a little trouble finding the correct way to make comparisons between dates.
I tried using the + and - operators to compare two DATETIMEs and the results don't make any sense to me.
For example:
1.
SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() - INTERVAL 1 HOUR
Outputs
2014-07-06 19:19:13 | 2014-07-06 18:19:13
These
SELECT UTC_TIMESTAMP() - DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR)
SELECT UTC_TIMESTAMP() - (UTC_TIMESTAMP() - INTERVAL 1 HOUR)
Both output 10000. This number doesn't make sense to me, but then it gets more confusing as this:
SELECT UTC_TIMESTAMP()-DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 SECOND)
Outputs 1. Why is that? What does that number represent?
2.
The manual page for date and time functions shows DATE_ADD() and DATE_SUB() can be used to add and subtract intervals from dates, but I don't see any functions in the manual that correspond to the great than and less than operators, so how would I check to see if the current date is greater than some other date?
I tried using the < and > operators and they seem to work, but I can't seem to find anything on this in the manual and want to make sure it's OK to use these operators like this:
SELECT UTC_TIMESTAMP() > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR)
Can anyone demystify DATETIME comparisons in MySQL?
To quote the documentation about UTC_TIMESTAMP():
Returns the current UTC date and time as a value in 'YYYY-MM-DD
HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function
is used in a string or numeric context.
Because the value is being used in the context of a number, it is treated as a number, which is the behavior that you see.
I've just found this out myself, but here's a quick example that shows you how it works.
#GordonLinoff's answer is neither here nor there, because your question isn't really about the format returned from utc_timestamp(). What you're really asking is what format does MySQL return when you use numeric operands + and - on timestamps.
I tend to agree with you that the documentation is a bit fuzzy on the topic. But this is what I found. You can build this view yourself to see the example in simpler terms.
create view cbhview as
select utc_timestamp() as nowtime,
utc_timestamp() - interval 1 hour as thentime,
date_sub(utc_timestamp(),INTERVAL 1 HOUR) as thentime2,
date_sub(utc_timestamp(),INTERVAL 1 SECOND) as justthentime;
select nowtime, thentime, thentime2, justthentime,
nowtime-thentime,
nowtime-justthentime,
thentime-thentime2
from cbhview;
+---------------------+---------------------+---------------------+---------------------+------------------+----------------------+--------------------+
| nowtime | thentime | thentime2 | justthentime | nowtime-thentime | nowtime-justthentime | thentime-thentime2 |
+---------------------+---------------------+---------------------+---------------------+------------------+----------------------+--------------------+
| 2014-07-06 20:22:58 | 2014-07-06 19:22:58 | 2014-07-06 19:22:58 | 2014-07-06 20:22:57 | 10000 | 1 | 0 |
+---------------------+---------------------+---------------------+---------------------+------------------+----------------------+--------------------+
1 row in set (0.00 sec)
100000 represents 1h 00min 00second
1 represents 1second
0 represents no difference between the two
In short, unless you know exactly what you're doing and exactly what you're trying to achieve, don't use numeric operands on date and timestamp datatypes. Keep to the functions that have been designed for the purpose date_add() and date_sub().