在设置DAG时,我们应该使用datetime库中的datetime.datetime类创建时间,并将其导入pytz库进行处理,以使其与时区相关联。以下是一个示例:
import datetime
import pytz
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
local_tz = pytz.timezone('Asia/Shanghai') # 设置本地时区
default_args = {
'owner': 'airflow',
'start_date': datetime.datetime(2021, 6, 1, tzinfo=local_tz), # 设置DAG的开始日期
}
with DAG('timezone_aware_dag', default_args=default_args, schedule_interval='@daily') as dag:
task_1 = BashOperator(task_id='task_1', bash_command='echo "hello world"')
task_2 = BashOperator(task_id='task_2', bash_command='echo "hello again"')
task_1 >> task_2
在这个例子中,我们把本地时区设置为“Asia/Shanghai”,并使用datetime.datetime类创建了开始日期,并将其与时区相关联。这样,当Airflow按计划运行DAG时,会将所有日期转换为指定时区中的等效日期。这对于避免时区感知DAG出现执行日期错误非常重要。