Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert field from timestamp to datetime

Tags:

sql

mysql

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?

like image 853
Oleg Avatar asked Jul 13 '14 08:07

Oleg


People also ask

Can we convert timestamp to date in SQL?

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.

How do I convert a time stamp to a date in Python?

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().


2 Answers

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.

like image 144
julienc Avatar answered Sep 22 '22 00:09

julienc


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;
like image 35
Ekaterina Avatar answered Sep 21 '22 00:09

Ekaterina