How to convert varchar “time” to real time in MySQL?

MySQLMySQLi Database

For this, you can use TIME_FORMAT(). Let us first create a table −

mysql> create table DemoTable1591
   -> (
   -> ArrivalTime varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1591 values('1620');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1591 values('2345');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1591 values('2210');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1591;

This will produce the following output −

+-------------+
| ArrivalTime |
+-------------+
| 1620        |
| 2345        |
| 2210        |
+-------------+
3 rows in set (0.00 sec)

Here is the query to convert varchar “time” to real time in MySQL −

mysql> select TIME_FORMAT(CONCAT(SUBSTRING(ArrivalTime, 1,2), ':', SUBSTRING(ArrivalTime, 3,4)), '%h:%i') from DemoTable1591;

This will produce the following output −

+---------------------------------------------------------------------------------------------+
| TIME_FORMAT(CONCAT(SUBSTRING(ArrivalTime, 1,2), ':', SUBSTRING(ArrivalTime, 3,4)), '%h:%i') |
+---------------------------------------------------------------------------------------------+
| 04:20                                                                                       |
| 11:45                                                                                       |
| 10:10                                                                                       |
+---------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 16-Dec-2019 06:49:47
Advertisements