Convert string with different format to date

后端 未结 2 1738
攒了一身酷
攒了一身酷 2021-01-06 14:46

I have a table with a string column (varchar(200)) that contain a date in different format. For example

may 24 1983 12:00AM
1981-01-13 00:00:00
1979         


        
2条回答
  •  走了就别回头了
    2021-01-06 15:38

    There's a trick for detecting a valid date on the man page. You can use it to determine whether a STR_TO_DATE format worked.

    select foo,
        case when length(date(str_to_date(foo,"%Y-%m-%d %H:%i:%S"))) is not null then str_to_date(foo,"%Y-%m-%d %H:%i:%S")
            when length(date(str_to_date(foo,"%b %d %Y %h:%i%p"))) is not null then str_to_date(foo,"%b %d %Y %h:%i%p")
        end as newdate
    from my_table
    

    Put one format for everyone you're expecting. Test like crazy.

    Good luck.

    (Oh, and congrats for trying to cleanup a bad schema!)

提交回复
热议问题