将TIME添加到DATETIME值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将TIME添加到DATETIME值相关的知识,希望对你有一定的参考价值。

我可以从文档中看到DATETIME_ADD仅适用于INT64值,而不是TIME对象。

我有一个DATETIME代表起点,然后是TIME对象的持续时间

WITH input AS (
  SELECT
    DATE(2018,03,05) AS start_date,
    TIME(5,0,0) AS start_time,
    TIME(8,0,0) AS duration
)

SELECT
  *,
  DATETIME(start_date,start_time) AS start_datetime,
  DATETIME_ADD(
      DATETIME_ADD(
        DATETIME_ADD(
          DATETIME(start_date,start_time), 
          INTERVAL EXTRACT(HOUR FROM duration) HOUR
        ),
        INTERVAL EXTRACT(MINUTE FROM duration) MINUTE
      ),
        INTERVAL EXTRACT(SECOND FROM duration) SECOND
    ) AS end_datetime

FROM input

有没有更好的方法将TIME对象的3个值(小时,分钟,秒)添加到给定的DATETIME对象?

答案

以下是BigQuery Standard SQL

WITH input AS (
  SELECT
    DATE(2018,03,05) AS start_date,
    TIME(5,0,0) AS start_time,
    TIME(8,0,0) AS duration
)
SELECT
  *,
  DATETIME(start_date,start_time) AS start_datetime,
  DATETIME_ADD(
      DATETIME_ADD(
        DATETIME_ADD(
          DATETIME(start_date,start_time), 
          INTERVAL EXTRACT(HOUR FROM duration) HOUR
        ),
        INTERVAL EXTRACT(MINUTE FROM duration) MINUTE
      ),
        INTERVAL EXTRACT(SECOND FROM duration) SECOND
    ) AS end_datetime,
    DATETIME_ADD(
      DATETIME(start_date,start_time), 
      INTERVAL DATETIME_DIFF(DATETIME(start_date,duration), DATETIME(start_date), SECOND) SECOND
    ) end_datetime_nicer_way
FROM input

以上是关于将TIME添加到DATETIME值的主要内容,如果未能解决你的问题,请参考以下文章

在 Python 中将 N 秒添加到 datetime.time 的标准方法是啥?

mysql中Timestamp,time,datetime 区别??

学习笔记:python3,代码片段(2017)

将Go的零时间。时间值插入MySQL DATETIME列错误

将 1 天添加到 DATETIME 格式值

python后端 flask框架 计算时间差 并根据时间差条件返回flag值