python - 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
并且渲染时没有显示任何日期。
我究竟做错了什么?
解决方案
您可以使用:
{{ (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") }}',
)
推荐阅读
- swift - 向 Spring 服务器发出 post 请求时出现 400 错误
- javascript - 使用 window.location.hostname 时生成了意外的 URL
- asp.net-core - 获取 DevExtreme DropDownBox 选定值
- php - 不推荐使用: call_user_func_array() 不应在 Symfony 路由器组件中静态调用
- testing - elixir 社区如何建议使用 chromedriver 设置集成测试?
- node.js - 使用 JQ 解析 XML -> XML2JS ->JSON.stringify 的结果
- pytorch - Pytorch:如何将参数矩阵沿两个维度重复为更大的矩阵?
- html - 在 Angular 的不同字段中存储选择选项元素的名称和值
- node.js - 使用节点 ncp 复制文件目录并缩小所有内容
- anylogic - 模型运行时资源池块左侧的 anylogic-color