Search code examples
jinja2dbt

Extract year from parameter in dbt


I am trying to extract to year, month , day from passed parameters in macros written in jinja. The passed input_date is string Below is my code

{% macro extract_year(input_date)%}
    Select date_part('year', CAST( {{ input_date }} as Date))
{% endmacro %}

Also tried

{% macro extract_year(input_date)%}
    MONTH(CAST({{ input_date }} as DATE))
{% endmacro %}

But I am getting an error So the cast itself is not working here Cast ' ' is invalid


Solution

  • It really depends on the format of the input date being passed in. If it's a str you could try putting quotes around the {{ input_date }}

    So it becomes:

    {% macro extract_year(input_date)%}
        Select date_part('year', CAST('{{ input_date }}' as Date))
    {% endmacro %}
    

    You might also need to specify the format of the date str being passed in