MySql, combining date and time column into a time

2019-01-23 11:17发布

问题:

I am guessing this is relatively simple to do, but I am unsure of the syntax. I have date and time columns that I want to combine to a timestamp column. how would I query this using a select?

回答1:

Mysql does not seem to have a constructor for datetime such as datetime('2017-10-26', '09:28:00'). So you will have to treat the component part as string and use string concatenation function (Note mysql does not have the || operator for string concatenation). If you want the datetime type, you will have to cast it.

concat(datefield,' ',timefield) as date

select cast(concat('2017-10-26', ' ', '09:28:00') as datetime) as dt;


回答2:

Or you could try the built-in TIMESTAMP(date,time) function.



回答3:

If it possible to use built-in function, just use it. Any way here is an example to find records between given timestamps.

SELECT `id` FROM `ar_time` WHERE TIMESTAMP(`cdate`,`ctime`) BETWEEN fromTimeStamp AND nowTimeStamp;


回答4:

For 24hr time

TIMESTAMP(Date, STR_TO_DATE(Time, '%h:%i %p'))


回答5:

SELECT * FROM tablename WHERE TIMESTAMP(datecol, timecol) > '2015-01-01 12:00:00';


回答6:

O.P. did say SELECT but in case anyone wants to add a timestamp column:

ALTER TABLE `t` ADD COLUMN `stamp` TIMESTAMP;
UPDATE `t` SET `stamp` = STR_TO_DATE(CONCAT(`Date`, ' ', `Time`), '%m/%d/%Y %H:%i:%s');

Adjust format strings to taste.