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. Let's generate a specific set of tests for your dbt models depending on the day of the week. Use the following YAML configuration for an existing dbt model:

example_model.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 %}

On weekdays, it would be rendered as:

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

However, on weekends, the same model would be rendered as:

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

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