You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLite如何对日期时间取整?求按秒、分钟截断时间的方法

SQLite 日期时间取整(移除秒数/分钟数)

用内置函数直接实现需求

1. 移除秒数(保留到分钟)

不管原时间的秒数是多少,直接截断到当前分钟的起始时刻,两种写法都可以:

-- 写法1:用strftime格式化后转datetime
SELECT datetime(strftime('%Y-%m-%d %H:%M:00', '2023-10-02 23:52:51'));
-- 输出:2023-10-02 23:52:00

-- 写法2:用datetime的start of minute参数,更简洁
SELECT datetime('2023-10-02 23:02:01', 'start of minute');
-- 输出:2023-10-02 23:02:00

2. 移除分钟数(保留到小时)

同样截断到当前小时的起始时刻:

-- 写法1:用start of hour参数
SELECT datetime('2023-10-02 23:02:01', 'start of hour');
-- 输出:2023-10-02 23:00:00

-- 写法2:用strftime格式化
SELECT datetime(strftime('%Y-%m-%d %H:00:00', '2023-10-02 23:02:01'));

创建自定义time_round函数(匹配示例调用方式)

如果想要像示例里那样用time_round(时间字符串, 单位)的形式调用,可以给SQLite注册自定义函数。下面以Python的sqlite3为例:

import sqlite3

def time_round(dt_str, unit):
    if unit == 'sec':
        return sqlite3.datetime(dt_str, 'start of minute')
    elif unit == 'min':
        return sqlite3.datetime(dt_str, 'start of hour')
    else:
        return dt_str  # 不支持的单位直接返回原时间

# 连接数据库(这里用内存数据库示例)
conn = sqlite3.connect(':memory:')
# 注册自定义函数
conn.create_function('time_round', 2, time_round)

# 测试调用
cursor = conn.cursor()
cursor.execute("SELECT time_round('2023-10-02 23:52:51', 'sec')")
print(cursor.fetchone()[0])  # 输出:2023-10-02 23:52:00

cursor.execute("SELECT time_round('2023-10-02 23:02:01', 'min')")
print(cursor.fetchone()[0])  # 输出:2023-10-02 23:00:00

其他语言(比如Java、C#)也可以通过对应SQLite驱动的API注册自定义函数,核心逻辑都是根据传入的unit参数,选择对应的时间截断规则。

内容的提问来源于stack exchange,提问作者Yiffany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:37:39