概要
Airflowのテンプレートに日付を埋め込む時に毎回ググってる気がしてきたので、自分用のまとめを書いた。
バージョン情報
- apache-airflow==1.10.3
参考URL
https://airflow.apache.org/macros.html
確認用スクリプト
contextの中にいるtsとかdsとかds_nodashとかにどういった値が入っているかを表示する為のDAG。
import airflow import datetime from airflow.operators.python_operator import PythonOperator args = { 'owner': 'masato watanabe', 'start_date': datetime.datetime(2019, 4, 20), } dag = airflow.DAG( 'test_dag', default_args=args, schedule_interval='0 0 * * *') def print_context(**context): print(context) PythonOperator( task_id='print_context', python_callable=print_context, provide_context=True, dag=dag)
これをairflow runで実行すると、ログの中にcontextの中身が表示される。
$ airflow run test_dag print_context 2019-04-22
contextの中身
表示されたcontextの中身から日付関連のものを抜粋。
キー名 | 値 | 意味 |
---|---|---|
ds | 2019-04-22 | 日付(%Y-%m-%d) |
ds_nodash | 20190422 | 日付(%Y%m%d) |
yesterday_ds | 2019-04-21 | 昨日日付(%Y-%m-%d) |
yesterday_ds_nodash | 20190421 | 昨日日付(%Y%m%d) |
tomorrow_ds | 2019-04-23 | 明日日付(%Y-%m-%d) |
tomorrow_ds_nodash | 20190423 | 明日日付(%Y%m%d) |
next_ds | 2019-04-23 | 次回実行時の日付(%Y-%m-%d) |
next_ds_nodash | 20190423 | 次回実行時の日付(%Y%m%d) |
prev_ds | 2019-04-21 | 前回実行時の日付(%Y-%m-%d) |
prev_ds_nodash | 20190421 | 前回実行時の日付(%Y%m%d) |
ts | 2019-04-22T00:00:00+00:00 | 日次(%Y-%m-%dT%H:%M:%S+00:00) |
ts_nodash | 20190422T000000 | 日次(%Y%m%dT%H%M%S) |
ts_nodash_with_tz | 20190422T000000+0000 | 日次(%Y%m%dT%H%M%S:0000) |
execution_date | <Pendulum [2019-04-22T00:00:00+00:00] | Pendulumで日付は持っている |
日付操作関連のmacro
1.10.3現在ではデフォルトのマクロの数はあまり多くない。
関数名 | 引数 | 内容 |
---|---|---|
ds_add | ds, days | %Y-%m-%dのdsに日数を加えて%Y-%m-%dで返す |
ds_format | ds, nput_format, output_format | dsのformatを変換する |
macroの追加
日付操作用のmacroを追加する。
仮に下記のようなts_nodashに指定秒を追加するマクロを記述してみる。
def ts_nodash_add(ts_nodash, add_seconds): ts = datetime.datetime.strptime(ts_nodash, '%Y%m%dT%H%M%S') ts += datetime.timedelta(seconds=add_seconds) return ts.strftime('%Y%m%dT%H%M%S')
DAGのuser_defined_macrosに関数を登録する。
dag = airflow.DAG( 'test_dag', default_args=args, user_defined_macros={'ts_nodash_add': ts_nodash_add}, schedule_interval='0 0 * * *')
echoで値を表示するだけのBashOperatorを生成し、3600秒ts_nodashを進めた結果を表示してみる。
BashOperator( task_id='echo_ts_add', bash_command='echo {{ts_nodash_add(ts_nodash, 3600)}}', dag=dag)
4/22の0時で実行する。
$ airflow run test_dag print_context 2019-04-22
当該ログを確認すると、1時間進んだ結果が表示されている。
INFO - Running command: echo 20190422T010000
改定履歴
Author: Masato Watanabe, Date: 2019-04-23 記事投稿