MySql, combining date and time column into a time stamp

前端 未结 6 1323
孤城傲影
孤城傲影 2020-12-14 14:32

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 th

相关标签:
6条回答
  • 2020-12-14 14:52

    For 24hr time

    TIMESTAMP(Date, STR_TO_DATE(Time, '%h:%i %p'))
    
    0 讨论(0)
  • 2020-12-14 14:58

    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;
    
    0 讨论(0)
  • 2020-12-14 15:07

    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;
    
    0 讨论(0)
  • 2020-12-14 15:08

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

    So then you would do something like this say from an Orders table...

    SELECT OrderNumber, TIMESTAMP(date,time) as OrderTS, SalesPersonID
    FROM Orders
    
    0 讨论(0)
  • 2020-12-14 15:12
    SELECT * FROM tablename WHERE TIMESTAMP(datecol, timecol) > '2015-01-01 12:00:00';
    
    0 讨论(0)
  • 2020-12-14 15:12

    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.

    0 讨论(0)
提交回复
热议问题