2

How can I convert a column with TIMESTAMP to DATETIME and retain the dates? I'm using PHPMyAdmin.

Also timestamp had the option to autofill, is there a way to do so in DATETIME? Or should I insert it each time with PHP?

thanks

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 1
    TIMESTAMP the column-type, or TIMESTAMP the unix-timestamp? – Wrikken Aug 03 '11 at 21:08
  • Be aware that TIMESTAMP (MySQ: datatype) is stored in GMT and converted to current session timezone for presentation. DATETIME is stored as-is, so converting from TIMESTAMP to DATETIME in timezone other than GMT may result in times being offset. – Mchl Aug 03 '11 at 21:18

3 Answers3

1
ALTER TABLE tablename MODIFY COLUMN columnname DATETIME;

(test on a test table first...)

No way to set the default to the current time save for triggers:

  DELIMITER $
  CREATE TRIGGER tablename_before_insert BEFORE INSERT ON tablename
  FOR EACH ROW 
  BEGIN
    IF NEW.columnname IS NULL THEN
      SET NEW.columnname = NOW();
    END IF;
    IF NEW.datum = '0000-00-00 00:00:00' THEN
      SET NEW.columnname = NOW();
    END IF;
  END$
  DELIMITER ;
Wrikken
  • 69,272
  • 8
  • 97
  • 136
1

If this query

ALTER TABLE table CHANGE `time` `time` datetime

will lose dates you can create new column then assign old values then delete old column and rename new one

ALTER TABLE table ADD `datetime` datetime AFTER `time`;
UPDATE table set datetime=time;
ALTER TABLE table DROP datetime;
ALTER TABLE CHANGE `datetime` `time` datetime

Read this:
This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

RiaD
  • 46,822
  • 11
  • 79
  • 123
-1

Use FROM_UNIXTIME() to convert from a unix timestamp into a regular datetime value.

A unix timestamp has no native type in mysql - it's simply an integer. timestamp fields will auto-populate, but only the first one in any given table. More details on that here.

Community
  • 1
  • 1
Marc B
  • 356,200
  • 43
  • 426
  • 500