【问题标题】:MySQL convert timestamp and time string to DateTime formatMySQL 将时间戳和时间字符串转换为 DateTime 格式
【发布时间】:2021-03-29 19:14:53
【问题描述】:

在我的表中有两列,一列作为时间戳保存日期,一列作为时间字符串保存带句点的时间。
例如:

我想在结果中将它们以 DateTime 格式组合成一列,然后按该列上的 desc 排序。

示例如下:http://sqlfiddle.com/#!9/25eb21/4
列名 'Datetime' 预期为 Datetime 或 timestamps 类型,因此我可以对其进行正确排序。

【问题讨论】:

标签: mysql sql datetime timestamp date-arithmetic


【解决方案1】:

您不需要将值转换为整数来添加它们。 MySQL为此目的内置了函数:

SELECT *,
       addtime(apptDate, str_to_date(apptTime, '%h:%i %p')) as datetime
FROM appt
ORDER BY Datetime DESC;

如果apptTime 只是一个time 值(它应该是),那么您显然不需要从字符串转换。我建议修复数据模型。

【讨论】:

  • 在我的 MySQL 服务器中,STR_TO_DATE() 函数总是返回 Null
  • @dangquang1020 。 . .它似乎确实适用于您提供的数据:dbfiddle.uk/…
【解决方案2】:

假设您要将作为字符串存储在列apptTime 中的持续时间添加到列apptDate 中的时间戳。

一种典型的方法是使用str_to_date() 将字符串转换为datetime,然后使用time_to_sec() 将时间部分转换为秒,然后我们可以使用日期算法将其添加到时间戳中。

所以

select t.*
    apptdate 
        + interval time_to_sec(str_to_date(appttime, '%h:%i %p')) second 
        as newapptdate
from mytable

【讨论】:

    【解决方案3】:
    select addtime(appDate, appTime) from ...
    

    您的 appDate 包含时间,可能是因为您正在应用时区。使用 convert_tz() 将您的两列转换为您的数据应该位于的时区,或者在添加之前使用 date(appDate) 提取其中的日期部分。不清楚哪一列是字符串,但 extract() 或 str_to_date() 是将文本解析为日期和/或时间的方法。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 2014-10-26
      • 2011-10-30
      • 2023-03-22
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多