Convert string (varchar) to timestamp format in MySQL?



To convert string to timestamp format, use STR_TO_DATE() along with DATE_FORMAT(). Let us first create a table −

mysql> create table DemoTable1602    -> (    -> ReportingDate varchar(40)    -> ); Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1602 values('Wed Oct 02 16:10:45 IST 2019'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1602 values('Fri May 31 13:00:10 IST 2019'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1602 values('Mon Dec 31 14:20:00 IST 2018'); Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1602;

This will produce the following output −

+------------------------------+ | ReportingDate                | +------------------------------+ | Wed Oct 02 16:10:45 IST 2019 | | Fri May 31 13:00:10 IST 2019 | | Mon Dec 31 14:20:00 IST 2018 | +------------------------------+ 3 rows in set (0.00 sec)

Following is the query to convert string to timestamp format in MySQL −

mysql> select date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') from DemoTable1602;

This will produce the following output −

+----------------------------------------------------------------------------------+ | date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') | +----------------------------------------------------------------------------------+ | 02-10-2019 16:10:45                                                              | | 31-05-2019 13:00:10                                                              | | 31-12-2018 14:20:00                                                              | +----------------------------------------------------------------------------------+ 3 rows in set (0.03 sec)
Updated on: 2019-12-16T07:37:06+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements