Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Airflow 2 : get execution date inside task

Tags:

python

airflow

I used to create tasks with the python operator and retrieve execution in airflow 1 as follow

def task(**kwargs):
    date = kwargs['execution_date']

What is the correct way to do it with the new taskflow api ? (probably missed it)

Thanks

like image 435
AFZ84 Avatar asked Jul 24 '26 03:07

AFZ84


1 Answers

You can access the execution context with get_current_context method:

from airflow.decorators import task
from airflow.operators.python import get_current_context

@task
def my_task():
    context = get_current_context()
    ti = context["ti"]
    date = context["execution_date"]

Docs here. Try it out!

Update:

The code above works just fine but, the so called context objects, are directly accesible in task-decorated functions. This means that there is no need to import get_current_context anymore. The context objects are accesible just by declaring the parameterss in the task signature:

@task
def my_task(ds=None, ti=None):
    print(f"execution_date:{ds}")
    print(f"task_instance:{ti}")
like image 148
NicoE Avatar answered Jul 27 '26 03:07

NicoE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!