首页 > 解决方案 > AIRFLOW:在 jinja 模板中为 {{ds}} 使用 .replace() 或 relativedelta()

问题描述

我的目标是根据气流宏变量 {{ds}} 返回上个月的第一天,并在 HiveOperator 中使用它。

例如对于 ds = 2020-05-09 我预计返回:2020-04-01

我找到并尝试过的解决方案是:

SET hivevar:LAST_MONTH='{{ (ds.replace(day=1) - macros.timedelta(days=1)).replace(day=1) }}';
SET hivevar:LAST_MONTH='{{ ds + macros.dateutil.relativedelta.relativedelta(months=-1, day=1) }}'

但两者都导致错误:

Error rendering template: replace() takes no keyword arguments 

Error rendering template: must be str, not relativedelta 

并且渲染时没有显示任何日期。

我究竟做错了什么?

标签: pythonmacrosairflow

解决方案


您可以使用:

{{ (execution_date + macros.dateutil.relativedelta.relativedelta(months=-1, day=1)).strftime("%Y-%m-%d") }}

例子:

from airflow.operators.bash_operator import BashOperator
default_args = {
    'owner': 'airflow',
    'start_date': datetime(2020, 4, 1),

}
with DAG(dag_id='stackoverflow',
         default_args=default_args,
         schedule_interval=None,
         catchup=False
         ) as dag:
    run_this = BashOperator(
        task_id='example',
        bash_command='echo ds is {{ ds }} modified ds is {{ (execution_date + macros.dateutil.relativedelta.relativedelta(months=-1, day=1)).strftime("%Y-%m-%d") }}',
    )

在此处输入图像描述


推荐阅读