<p>有两种方法可以做到这一点</p>
<ol>
<li>创建自己的宏,如<a href="https://github.com/apache/airflow/blob/2.0.0/airflow/macros/__init__.py#L29-L46" rel="nofollow noreferrer">ds_add</a>,并将其放在<a href="https://airflow.apache.org/docs/apache-airflow/stable/plugins.html" rel="nofollow noreferrer">plugin</a>中</李>
<li>在Jinja模板中使用python代码</李>
</ol>
<p>选项2是最简单、最直接的方法</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
from airflow.models import DAG
from airflow.operators.python import PythonOperator
dag = DAG(
dag_id="trigger_dag",
start_date=datetime(2021, 3, 10),
catchup=True,
schedule_interval='@once',
)
with dag:
op = PythonOperator(
task_id='a',
python_callable=lambda x, y: print(x, y),
op_args=[
'{{ ts_nodash }}',
'{{ execution_date.subtract(seconds=2).strftime("%Y%m%dT%H%M%S") }}',
],
)
</code></pre>
<p>获取<code>ts_nodash</code>的方式如<a href="https://github.com/apache/airflow/blob/2.0.0/airflow/models/taskinstance.py#L1527" rel="nofollow noreferrer">how the context is built</a>所示。我们基本上是在datetime对象的基础上构建的,该对象将被格式化为字符串</p>
<p>以下是任务的呈现模板视图</p>
<p><a href="https://i.stack.imgur.com/9vYxZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9vYxZ.png" alt="enter image description here"/></a></p>