How to convert string to 24-hour datetime format in MySQL?


To convert string to 24 hour datetime format in MySQL, you can use STR_TO_DATE() method. With that use the following format for datetime as the parameter:

'%Y-%m-%d %H:%i:%s'

Following is the syntax

SELECT STR_TO_DATE(yourColumnName, '%Y-%m-%d %H:%i:%s') FROM yourTableName;

Let us first create a table:

mysql> create table DemoTable (ArrivalDate varchar(200));
Query OK, 0 rows affected (0.57 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values('2019-01-31 15:45:23');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('2012-12-12 20:30:26');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('2016-06-07 21:04:05');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2017-02-03 19:24:32');
Query OK, 1 row affected (0.27 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output

+---------------------+
| ArrivalDate         |
+---------------------+
| 2019-01-31 15:45:23 |
| 2012-12-12 20:30:26 |
| 2016-06-07 21:04:05 |
| 2017-02-03 19:24:32 |
+---------------------+
4 rows in set (0.00 sec)

Following is the query to convert string to 24-hour datetime format in MySQL:

mysql> select str_to_date(ArrivalDate,'%Y-%m-%d %H:%i:%s') AS `24HourFormat` from DemoTable;

This will produce the following output:

+---------------------+
| 24HourFormat        |
+---------------------+
| 2019-01-31 15:45:23 |
| 2012-12-12 20:30:26 |
| 2016-06-07 21:04:05 |
| 2017-02-03 19:24:32 |
+---------------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements