Skip to content
Advertisement

How to convert varchar to datetime, not working

I have imported some columns from a textfile into my table stuff.

I had to import date as varchar(255). I want to convert datatype from varchar to datetime.

The format of date data is:

I have tried the following without success :

and :

Advertisement

Answer

The syntax of your queries is not correct.

STR_TO_DATE() is indeed meant to convert a string to a date. As a second argument, it expects a string (not a litteral string !) that represents the format of the input string.

Given the format of your date, you may use :

Format specifier details :

  • %e : Day of the month, numeric (0..31)
  • %c : Month, numeric (0..12)
  • %Y : Year, numeric, four digits
  • %l : Hour (1..12)
  • %i : Minutes, numeric (00..59)
  • %s : Seconds (00..59)
  • %p : AM or PM

Demo on DB Fiddle


If you are actually looking to convert the datatype of the column, then you would need to create a temporary column, update it with converted data, then drop the original column and rename the temporary, like :

If you are using MySQL 8.0, the last statement can be written as :

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement