doujia6503 2014-05-07 11:21
浏览 39
已采纳

在MySQL中将列的格式更改为时间戳

I have a CSV file that I am importing into MySQL using PHP but the problem is that the timestamp is in the following format

01/02/2014 00:00:00

I have read about MySQL timestamp and it only accepts in the following format

01-02-2014 00:00:00 

from what I know. I am wondering if there is a way that I can convert the column which I have set as varchar into timestamp and convert it into a format that MySQL will accept ?

Is there an SQL query or a PHP function that I can use to do this? Also, the no of rows exceeds more than a million so I want it to be as fast as possible.

Any suggestions would be appreciated.

  • 写回答

2条回答 默认 最新

  • doulan9188 2014-05-07 11:32
    关注
    1. If your MySQL column is DATE type:

    $date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

    1. If your MySQL column is DATETIME type:

    $date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

    You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.

    Update, the way your date is formatted you can't use strtotime(), use this code instead:

    $date = '02/07/2009 00:07:00';
    $date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date); 
    echo $date;
    

    Output:

    2009-07-02 00:07:00

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部