Skip to main content

How to Use Python's Datetime Modules in Jinja

The DataOps.live template rendering engine supports using Python's datetime and time modules in your Jinja templates. Leveraging Python lets you use date- and time-related operations in your templates.

Let's use the time module and generate specific tests for your dbt models depending on the day of the week:

  1. Use the following YAML configuration for an existing dbt model:

    example_model.template.yml
    - name: ADDRESS_ID
    description: 'ID of the address'
    tests:
    # Monday is 0, Tuesday is 1, Wednesday is 2, Thursday is 3, Friday is 4, Saturday is 5, Sunday is 6
    {% if time.gmtime().tm_wday >=0 and time.gmtime().tm_wday <=4 %}
    - weekday_test
    {% else %}
    - weekend_test
    {% endif %}
  2. Add the variable DATAOPS_REMOVE_RENDERED_TEMPLATES: 1 in your variables.yml in the project settings and not within your job. Otherwise, you may get issues when running your pipeline.

    This should successfully render the above Jinja template. See Template rendering the DataOps way for more information about YAML config files.

On weekdays, it is rendered as:

example_model.template.yml
- name: ADDRESS_ID
description: "ID of the address"
tests:
- weekday_test

However, on weekends, the same model is rendered as:

example_model.template.yml
- name: ADDRESS_ID
description: "ID of the address"
tests:
- weekend_test

The example above refers to the time module, but you can similarly use all functionalities available in both time and datetime.