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

在Python脚本的DuckDB内存模式中如何获取当年的第一天日期?

在Python脚本的DuckDB内存模式中如何获取当年的第一天日期?

嗨,我刚好之前也遇到过类似的需求,DuckDB里确实没有直接的current_year函数,但有几种干净又简洁的方式来获取当年的第一天,完全符合你想要的整洁风格~

方法1:用date_trunc截断日期(最推荐)

date_trunc是DuckDB里专门用于日期截断的工具函数,指定'year'作为截断单位,就能直接得到当年的1月1日,返回的是标准的日期类型,不需要额外转换。

在Python脚本里的使用示例:

import duckdb

# 连接内存模式的DuckDB
con = duckdb.connect()

# 获取本地时区的当年第一天
first_day_local = con.execute(
    "SELECT date_trunc('year', current_date) AS first_day_of_year"
).fetchone()[0]
print(f"本地时区当年第一天:{first_day_local}")

# 如果你需要UTC时区的日期,把current_date换成today()就行
first_day_utc = con.execute(
    "SELECT date_trunc('year', today()) AS first_day_of_year_utc"
).fetchone()[0]
print(f"UTC时区当年第一天:{first_day_utc}")

方法2:年份提取+字符串拼接

如果你更喜欢直观看到日期的构造逻辑,可以先提取当前年份,再拼接成YYYY-01-01的格式,最后转换为日期类型:

import duckdb

con = duckdb.connect()

first_day = con.execute(
    "SELECT concat(extract(year from current_date), '-01-01')::date AS first_day_of_year"
).fetchone()[0]
print(f"当年第一天:{first_day}")

这种方式也很清晰,而且结果和date_trunc完全一致,看你个人习惯选择就好~

备注:内容来源于stack exchange,提问作者supernova

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 15:57:59