MySQL query to convert a string like “1h 15 min” into 75 minutes?


You can use str_to_date() for this conversion. Let us first create a table −

mysql> create table DemoTable
   (
   stringDate varchar(100)
   );
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('1h 15 min');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('2h 30 min');
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+------------+
| stringDate |
+------------+
| 1h 15 min  |
| 2h 30 min  |
+------------+
2 rows in set (0.00 se

Following is the query to convert string a string like "1 h 15 min" into 75 i.e. 75 minutes −

mysql> select
time_to_sec(str_to_date(stringDate, '%l h %i min')) / 60 second
from DemoTable
having second is not null
union all
select
time_to_sec(str_to_date(stringDate, '%i min')) / 60 second
from DemoTable
having second is not null;

Output

+----------+
| second   |
+----------+
| 75.0000  |
| 150.0000 |
+----------+
2 rows in set, 2 warnings (0.04 sec)

Updated on: 30-Jul-2019

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements