蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 SQLite 3.53 确定性 strftime() 日期格式化、自定义模板与 format() 数值格式化实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-func-format.py
explore-func-format.py133 行
"""SQL FORMAT() / strftime() 离线实验:验证确定性 YYYY-MM-DD 日期格式化、自定义日期模板与数值格式化。"""
import json
import platform
import sqlite3


def seed_websites(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE websites (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            url TEXT NOT NULL,
            alexa INTEGER NOT NULL,
            country TEXT NOT NULL
        );
        INSERT INTO websites (id, name, url, alexa, country) VALUES
            (1, 'Google', 'https://www.google.com/', 1, 'USA'),
            (2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
            (3, '蓝色天空', 'http://www.mbsky.com/', 4689, 'CN'),
            (4, '微博', 'http://weibo.com/', 20, 'CN'),
            (5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
            (7, 'stackoverflow', 'http://stackoverflow.com/', 0, 'IND');
        """
    )


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    seed_websites(conn)
    cases = []

    # Case 1: Deterministic YYYY-MM-DD formatting with strftime('%Y-%m-%d', ...)
    fixed_ts = "2026-05-15 09:45:00"
    cur1 = conn.execute(
        "SELECT name, url, strftime('%Y-%m-%d', ?) AS date FROM websites ORDER BY id;",
        (fixed_ts,),
    )
    cols1 = [d[0] for d in cur1.description]
    rows1 = [list(r) for r in cur1.fetchall()]
    exp1 = {
        "columns": ["name", "url", "date"],
        "rows": [
            ["Google", "https://www.google.com/", "2026-05-15"],
            ["淘宝", "https://www.taobao.com/", "2026-05-15"],
            ["蓝色天空", "http://www.mbsky.com/", "2026-05-15"],
            ["微博", "http://weibo.com/", "2026-05-15"],
            ["Facebook", "https://www.facebook.com/", "2026-05-15"],
            ["stackoverflow", "http://stackoverflow.com/", "2026-05-15"],
        ],
    }
    act1 = {"columns": cols1, "rows": rows1}
    cases.append(
        {
            "name": "strftime_yyyy_mm_dd_websites",
            "summary": "使用确定性时间 2026-05-15 09:45:00 与 strftime('%Y-%m-%d', ...) 格式化日期列",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Multiple deterministic date format patterns with strftime()
    fmts = conn.execute(
        """
        SELECT
            strftime('%Y/%m/%d', ?),
            strftime('%Y年%m月%d日 %H:%M', ?),
            strftime('%Y-W%W', ?);
        """,
        (fixed_ts, fixed_ts, fixed_ts),
    ).fetchone()
    exp2 = {
        "slash_date": "2026/05/15",
        "cn_datetime": "2026年05月15日 09:45",
        "year_week": "2026-W19",
    }
    act2 = {
        "slash_date": fmts[0],
        "cn_datetime": fmts[1],
        "year_week": fmts[2],
    }
    cases.append(
        {
            "name": "strftime_custom_date_templates",
            "summary": "验证斜杠日期、中文日期时间及年周编号等多种确定性日期格式模板",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: SQLite format()/printf() numeric & string formatting vs DATE_FORMAT dialect
    fmt_num = conn.execute(
        "SELECT format('%,d', 1234567), format('%.2f', 4689.5), format('#%04d %s', 7, 'SQL');"
    ).fetchone()
    df_err = None
    try:
        conn.execute("SELECT DATE_FORMAT('2026-05-15', '%Y-%m-%d');")
    except sqlite3.OperationalError as exc:
        df_err = str(exc)
    exp3 = {
        "thousands_int": "1,234,567",
        "fixed_two_decimals": "4689.50",
        "padded_label": "#0007 SQL",
        "sqlite_has_no_date_format": True,
    }
    act3 = {
        "thousands_int": fmt_num[0],
        "fixed_two_decimals": fmt_num[1],
        "padded_label": fmt_num[2],
        "sqlite_has_no_date_format": bool(df_err and "no such function" in df_err.lower()),
    }
    cases.append(
        {
            "name": "sqlite_format_printf_and_dialect_check",
            "summary": "验证 SQLite format() 按 printf 规范格式化千分位与小数,并核实 DATE_FORMAT 为 MySQL 专有函数",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/sql-func-format-lab/explore-func-format.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-func-format.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip

下载课程关联工程包:SQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1543.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习