0

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.

nbanic
  • 1,270
  • 1
  • 8
  • 11
Bazinga777
  • 5,140
  • 13
  • 53
  • 92
  • Import your file into a staging table where all columns are text. Process as necessary and write to your real table from the staging table. – Dan Bracuk May 07 '14 at 19:35

2 Answers2

2
  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

itsbalamurali
  • 192
  • 1
  • 2
  • 10
1

You will see in the following link (Convert one date format into another in PHP) that One can use either DateTime or strtotime() with date() to create the new format.

I would use the DateTime:

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

This solution is given by the php documentation.(http://php.net/manual/en/datetime.createfromformat.php)

Community
  • 1
  • 1
Louis Milotte
  • 49
  • 2
  • 8