I have a legacy database where there is table that has fields: start_date TIMESTAMP, expiration_date DATETIME.
It cause issues with some queries if database is used on database with different timezones. So to avoid them, I want to convert start_date to DATETIME. How could I safely convert from TIMESTAMP to DATETIME? Won't I lose any data if I change type of start_date from TIMESTAMP to DATETIME? How will mysql convert dates TIMESTAMP to DATETIME?
CAST() function performs the same way as CONVERT(), i.e. it too converts the value of any data type in the desired data type. Thus, we can make use of this function to convert the retrieved current timestamp in the date and time values.
Converting timestamp to datetime We may use the datetime module's fromtimestamp() method to convert the timestamp back to a datetime object. It returns the POSIX timestamp corresponding to the local date and time, as returned by time. time().
This is how I would do it:
1) Create a new datetime
column
ALTER TABLE mytable ADD COLUMN mydatetime DATETIME;
2) Update this column using the timestamp values
UPDATE mytable SET mydatetime=FROM_UNIXTIME(UNIX_TIMESTAMP(mytimestamp));
3) After a few integrity checks, delete the timestamp
column
ALTER TABLE mytable DROP COLUMN mytimestamp;
This should be safe enough for you, as you can keep the original timestamp
column as long as you want.
Here is a sqlfiddle example.
In MySQL you can simply change the datatype from TIMESTAMP
to DATETIME
with no loss of data:
ALTER TABLE table_name MODIFY start_date DATETIME;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With