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

如何保留Airflow执行日期的日期部分并将时间设为00:00

如何在Airflow中将execution_date调整为指定时区的当日零点并格式化?

你不需要用pendulum.parse,因为execution_date本身就是pendulum.DateTime对象,直接调用它的方法就能实现需求。这里有两种可行的方式:

方式1:在Jinja模板中直接处理

直接在模板里将execution_date转换到阿姆斯特丹时区,然后取当日零点,再格式化为你需要的字符串格式:

time_marker = "{{ execution_date.in_timezone('Europe/Amsterdam').start_of('day').strftime('%Y%m%dT%H:%M:%S') }}"

执行后会得到类似20240115T00:00:00的结果,不管任务在执行日期的哪个时间点运行,都会锁定到当日零点。

方式2:在Python任务中处理(脱离Jinja模板)

如果是在PythonOperator的任务函数里处理,可以直接操作pendulum对象:

from airflow.decorators import task
import pendulum

@task
def get_time_marker(execution_date):
    amsterdam_tz = pendulum.timezone('Europe/Amsterdam')
    # 转换时区并设置为当日起始时间(零点)
    adjusted_dt = execution_date.in_timezone(amsterdam_tz).start_of('day')
    # 格式化为目标字符串
    time_marker = adjusted_dt.strftime('%Y%m%dT%H:%M:%S')
    return time_marker

为什么pendulum.parse没用?

pendulum.parse的作用是把字符串解析成datetime对象,而execution_date本身已经是pendulum的datetime实例,所以用parse属于多此一举,自然达不到预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:22:08