AIRFLOW:在 jinja 模板中为 {{ds}} 使用 .replace() 或relativedelta()

Mat*_*ski 3 python macros airflow

我的目标是根据气流宏变量 {{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) }}'
Run Code Online (Sandbox Code Playgroud)

但两者都导致了错误:

Error rendering template: replace() takes no keyword arguments 

Error rendering template: must be str, not relativedelta 
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Ela*_*lad 6

您可以使用:

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

例子:

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") }}',
    )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述