如何在Airflow DAG代码中加入run_date?Python新手如何命名含日期的表?
Airflow相关问题解答
1. 在Airflow DAG代码中加入run_date(执行日期)
Airflow中任务的执行日期(对应你说的run_date)可通过模板变量直接获取,常用变量包括:
{{ ds }}:格式为YYYY-MM-DD的日期字符串{{ ds_nodash }}:格式为YYYYMMDD的无连字符日期字符串{{ execution_date }}:完整datetime对象,可通过.strftime()自定义格式
结合你提供的TelegramOperator示例,直接在text字段中嵌入模板变量即可:
from airflow import DAG from airflow.operators.telegram_operator import TelegramOperator from datetime import days_ago telegram_chat_id = "你的目标聊天ID" with DAG("inform_status", schedule_interval="55 17 * * 1-5", start_date=days_ago(1), catchup=False, tags=["Adb"]) as dag: task5 = TelegramOperator( task_id='task5', telegram_conn_id='telegram_conn', # 使用ds变量作为时间戳,也可替换为ds_nodash或自定义格式 text='Report of {{ ds }}_table_name:\n {Query_result}', chat_id=telegram_chat_id, dag=dag )
如果需要自定义日期格式(如YYYY年MM月DD日),可以这样写:
text='Report of {{ execution_date.strftime("%Y年%m月%d日") }}_table_name:\n {Query_result}'
2. 为数据表命名时包含日期
作为Python新手,有两种简单实现方式:
方式一:在SQL语句中直接使用模板变量
如果通过SQL操作创建表,直接在表名中嵌入{{ ds_nodash }}这类变量即可:
from airflow.operators.postgres_operator import PostgresOperator create_table_task = PostgresOperator( task_id='create_date_table', postgres_conn_id='你的数据库连接ID', # 表名拼接无连字符日期 sql=""" CREATE TABLE IF NOT EXISTS data_table_{{ ds_nodash }} ( id SERIAL PRIMARY KEY, content TEXT ); """, dag=dag )
方式二:在Python函数中通过上下文获取执行日期
如果用PythonOperator处理表名,可通过context参数获取执行日期并格式化:
from airflow.operators.python_operator import PythonOperator def create_table_with_date(**context): # 从上下文提取执行日期 exec_date = context['execution_date'] # 格式化为YYYYMMDD格式的字符串 date_str = exec_date.strftime("%Y%m%d") table_name = f"data_table_{date_str}" # 此处编写创建表的业务逻辑(如数据库连接、执行建表语句) print(f"即将创建数据表:{table_name}") create_table_task = PythonOperator( task_id='create_table_with_date', python_callable=create_table_with_date, # 开启上下文传递 provide_context=True, dag=dag )
内容的提问来源于stack exchange,提问作者Umid Umaraliev
相关产品推荐
相关产品推荐

