Update only Time in a mysql DateTime field

前端 未结 12 1430
北海茫月
北海茫月 2020-12-09 07:44

How can I update only the time in an already existing DateTime field in MySQL? I want the date to stay the same.

相关标签:
12条回答
  • 2020-12-09 08:03

    This what helped me. I convert time to minutes firstly: 150 for 2:30 am.

    UPDATE lesson SET starts_at = DATE_ADD(Date(starts_at), INTERVAL 150 MINUTE)
    

    Minutes are enough accurate for me, though you can use other units: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add

    0 讨论(0)
  • 2020-12-09 08:08

    I used ADDTIME in the following way

    Earlier in my cloud server, the DateTime was set to UTC but after changing the DateTime to Asia/Kolkata ie UTC 5:30 I wanted the same to reflect in my database tables.

    I wanted to update the created_at and updated_at column by 5 hours 30 minutes. I did the following

    To update all the rows of the table

    UPDATE 
        products 
    SET 
        created_at = ADDTIME(created_at, '5:30:0'), 
        updated_at = ADDTIME(updated_at, '5:30:0') 
    

    You can omit the WHERE condition if you want to update all the records, but since my new records were updated with proper values. So only my rows below id less than 2500 must be updated

    UPDATE 
        products 
    SET 
        created_at = ADDTIME(created_at, '5:30:0'), 
        updated_at = ADDTIME(updated_at, '5:30:0') 
    WHERE
        id < 2500;
    
    0 讨论(0)
  • 2020-12-09 08:09

    Try this:

    UPDATE t1 SET DateTimeField = CONCAT(DATE(DateTimeField),' 12:34:56');
    
    0 讨论(0)
  • 2020-12-09 08:09

    Try this:

    UPDATE sms 
    SET entry_period_end_date= entry_period_end_date+INTERVAL 6 Hour 
    WHERE TIME(entry_period_end_date) = '06:00:00';
    
    0 讨论(0)
  • 2020-12-09 08:10

    MySQL DEV page shows functions like subtime and difftime

    A sample code to back the time all posts in 3 hours is above:

    UPDATE tablepost SET datepost = SUBTIME( datepost , '0 3:0:0' );
    

    Note that values 0 dont alter the respective field. Take care this code, use select first to test these function.

    Reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_subtime

    0 讨论(0)
  • 2020-12-09 08:14

    Well, exactly what you are asking for is not possible. The date and time components can't be updated separately, so you have to calculate the new DateTime value from the existing one so that you can replace the whole value.

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