Jinja filters

To work with your data in Jinja, you often need to pick and modify specific parts of it. Filters let you do this. A filter is a pure function: it takes your data as input and returns a modified version without side effects, so the original data stays unchanged. Despite the name, filters aren't limited to reducing data. This article covers the most important filters and lists the rest.

Filter syntax

To apply a filter, add the pipe symbol | after your variable or data structure, followed by the filter name. You can read the pipe as "such that." For example, the upper filter takes a string and returns it in uppercase, so {{ customer["name"] | upper }} reads as output the customer name such that its letters are uppercase.

Filters and arguments

Filters are functions, so they take at least one argument. The first (main) argument is the value before the pipe symbol. If a filter needs extra arguments, include them in round brackets after the filter name. Otherwise, the brackets are optional. In the descriptions below, square brackets mark optional arguments, including those with a default value.

For example, the replace filter takes a string and two required extra arguments, and replaces all occurrences of the first with the second.

{# Filter without extra arguments #}
{{ "orange" | upper }} 
{{ "orange" | upper() }}
// both work and output "ORANGE"

{# Filter with extra arguments #} 
{{ "apple" | replace }} 
// throws an error because the arguments are missing
{{ "apple" | replace('p', 'b') }} 
// works and outputs "abble"

Filters that create or work on lists return generator objects instead of lists. This applies to batch(), map(), slice(), select(), selectattr(), reject(), and rejectattr(). To convert the result back to a list, add the list filter at the end.

{% set arr = [1, 2, 3] %}

{% set arr = arr | batch(1) %} 

{# prints the generator object #}
{{ arr }}

{# prints the list of batches #}
{{ arr | list }}

Applying string filters to non-string variables casts them to strings.

{% set o = ['b1', 'a1', 'c1'] %}

{{ 'List length: ' ~ o | count }}

{% set o = o | upper  %}

{{ 'String length: ' ~ o | count }}

{# Prints:
List length: 3
String length: 18
#}

Chaining filters

You can chain filters as long as the output type of one filter matches the input type of the next. Filters are evaluated left to right. For example, {{ "apple" | upper | replace('P', 'b') }} outputs "AbbLE", but {{ "apple" | replace('P', 'b') | upper }} outputs "APPLE", because "apple" has no uppercase P to replace.

Available filters

For the full list, see the Jinja reference. Bloomreach's implementation of Jinja doesn't support some of the built-in filters.

Not supported filters

  • groupby()
  • tojson()
  • max()
  • min()

Filters that modify strings

b64encode(value, [encoding])
Parameters: String value to be encoded, Optional encoding
Output: the input string encoded in Base64.
Encodes a string into a Base64 sequence. Optionally, specify an encoding as the second argument, and the filter applies str.encode() with it. For possible encodings, see Standard encodings.
Base 64 URL encoding example
Encodes a string URL, equivalent to using the JavaScript base64url.encode(value).

{% set data_encoded = '{"sub":"1234567890","name":"John Doe","iat":1516239022}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "") %}

b64decode(value, [encoding])
Parameters: String value, Optional encoding
Output: the input string decoded from Base64.g.
Decodes a string interpreted as a Base64 sequence. Optionally, specify an encoding as the second argument, and the filter applies str.encode() with it. For possible encodings, see Standard encodings.

center(value, width=80)
Parameters: String value, Number width
Output: the input string centered in a field of the given width.
Centers the value in a field of the given width, adding spaces on both sides as needed. Similar to str.center(), str.ljust() or str.rjust().

capitalize(value)
Parameters: String value
Output: the input string with its first character in uppercase and all others in lowercase.
Equivalent to str.capitalize()

escape(value) or e(value)
Parameters: String value
Output: the input string with &, <, >, ' (single quote), and " (double quote) converted to HTML-safe sequences.
Use this filter to display text that might contain these characters in HTML. It marks the return value as a markup string.

forceescape(value)
Parameters: String value
Output: the input string with &, <, >, ' (single quote), and " (double quote) converted to HTML-safe sequences.
Similar to escape(), but it also forces the output of macros to be escaped.

format(value, \* args, \* \*kwargs)
Parameters: String value, Either *args or ** kwargs
Output: the input string formatted with old-style Python formatting.
Applies old-style Python string formatting (%) to an object. For details, see Old python formatting. For supported types and formatting codes, see print style formatting in the Python docs.

hash(value, hash_fn, input_encoding='utf-8', output_encoding='hex')
Parameters: String value, String the type of the hash, Optional input encoding, Optional output encoding
Output: the input value hashed with the given hash type.
Returns a hashed string. Available algorithms for hash_fn are md5, sha1, sha224, sha256, sha384, and sha512. For possible input encodings, see Standard encodings. Supported output encodings are hex and base64.

hmac(key, message, hash_fn, input_encoding='utf-8', output_encoding='hex')
Parameters: String value as the key, String value as the message, String the type of the hash, Optional encoding
Output: an HMAC string.
Returns a hash-based message authentication code string based on the supplied key and message. Available algorithms for hash_fn are md5, sha1, sha224, sha256, sha384, and sha512. For possible input encodings, see Standard encodings. Supported output encodings are hex and base64.

For example, to generate a JWT token you could use the following code:

{# generate base64url-encoded strings out of JSONs #}
{# replace calls are needed to convert the string from usual base64 to base64url #}
{% set header_encoded = '{"alg":"HS256","typ":"JWT"}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "")  %}
{% set data_encoded = '{"sub":"1234567890","name":"John Doe","iat":1516239022}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "") %}
{% set data = header_encoded ~ "." ~ data_encoded %}
{# call hmac filter #}
{% set signature = "secretkey" | hmac(msg=data, hash_fn="sha256", output_encoding="base64") | replace("/", "_") | replace("+", "-") | replace("=", "") %}
{{ header_encoded ~ "." ~ data_encoded ~ "." ~ signature }}
{# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.8TLPbKjmE0uGLQyLnfHx2z-zy6G8qu5zFFXRSuJID_Y #}

indent(value, width=4, first=False, blank=False)
Parameters: String value, Number width, Boolean first, Boolean blank
Output: the input string with each line indented by the given width.
Returns a copy of the string with each line indented by 4 spaces by default. The first line and blank lines aren't indented by default.

  • width: the number of spaces to indent by.
  • first: indents the first line.
  • blank: indents empty lines.

lower(value)
Parameters: String value
Output: the input string with all characters in lowercase.
Similar to str.lower().

pprint(value, verbose=False)
Parameters: String value, Optional Boolean verbose
Output: the input value formatted for readability.
Pretty-prints a variable, for example, by printing dictionary pairs on separate lines. Useful for debugging.

replace(value, old, new, count=None)
Parameters: String value, String old, String new, Integer Optional count
Output: the input string with all (or the first count) occurrences of old replaced with new.
Similar to str.replace().

remove_accents(value)
Parameters: String value
Output: the input string with accents removed.
Attempts to remove accents from non-ASCII characters. For example, it converts "Déjà vu" to "Deja vu".

title(value),
Parameters: String value
Output: the input string in English title case.
Starts each word with an uppercase letter and puts all remaining characters in lowercase. Same as str.title().

trim(value)
Parameters: String a value from which white spaces will be trimmed
Output: the input string with leading and trailing whitespace removed.
Same as the default behavior str.strip().

striptags(value)
Parameters: String value
Output: the input string with SGML/XML tags removed.
Also replaces adjacent whitespace with one space.

truncate(value, length=255, killwords=False, end='...', )
Parameters: String value, Integer length, Optional Boolean killword, Optional String end
Output: the input string reduced to the given number of characters.
Returns a truncated copy of the string. length defaults to 255. If killwords is true, the filter cuts the text exactly at length. Otherwise, it discards the last partial word. If the text was truncated, the filter appends the end string (default ...). Strings that exceed the length by less than the tolerance margin given in the fourth parameter aren't truncated.

upper(value)
Parameters: String value
Output: the input string with all characters in uppercase.
Same as str.upper().

urldecode(value)
Parameters: String value
Output: the input value in URL encoding.
Decodes a string from URL-compatible encoding (UTF-8). For details, see the HTML URL Encoding Reference.

urlencode(value)
Parameters: String value
Output: the input value encoded in the URL encoding
Escapes strings for use in URLs (UTF-8). It accepts dictionaries, regular strings, and pairwise iterables. For details, see the HTML URL Encoding Reference

🚧

Urlencode in Jinja

When given a string, urlencode doesn't quote /. HTTP servers treat / and %2F equivalently in paths. If you need quoted slashes, use the |replace("/", "%2F") filter.

urlize(value, trim_url_limit=None, nofollow=False, target=None)
Parameters: String value, Optional Integer trim_ur_limit, Optional Boolean nofollow, Optional String target
Output: the input string with URLs wrapped in HTML <a> tags.
Converts URLs in plain text into clickable links by wrapping them in tags with the href property.

wordwrap(value, width=79, break_long_words=True, wrapstring=None)
Parameters: String value, Number width (optional), default = 79, Boolean breaklong_words (optional), default = True, String_ wrapstring, default = None.
Output: the input string wrapped with the wrapstring.
Returns a copy of the string wrapped after 79 characters by default. Use width to override this. If you set break_long_words to false, Jinja doesn't split words longer than width. By default, the line breaks are the newlines of the environment. Use wrapstring to change them.

hexencode(value, [encoding])
Parameters: String value to be encoded, Optional encoding
Output: the input string encoded in hexadecimal.

hexdecode(value, [encoding])
Parameters: String value, Optional encoding
Output: the input string decoded from hexadecimal.

{% set long_string %}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
{% endset %}

{{ long_string | wordwrap(width=45, break_long_words=True, wrapstring="<br>") }}

{# Outputs:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
#}

More on the format filter

The format filter accepts either positional arguments (args), which are assigned sequentially to the % placeholders, or keyword arguments (kwargs) in the form keyword=value. Jinja string formatting doesn't support formatting variables from a dictionary. Instead, pass the values as variable=value keyword arguments.

{# Example of using args #}
{{ '%s after %s, %d by %d' | format('One', 'another', 1, 1) }}
// prints 'One after another, 1 by 1'
{# Example of using kwargs #} 
{{ 'These %(items)s have %(verb)s argument order.'|format(verb='swapped', items='words') }}
// prints 'These words have swapped argument order.'
🚧

Format filter

You can't mix positional and keyword arguments. Doing so throws an error, so choose one.

Filters that modify numbers

abs(Number)
Parameters: a Number
Output: the absolute value of the number.

round(value, precision=0, method='common')
Parameters: Float value, Optional Integer precision, Optional String method
Output: the input number rounded to the given precision with the given method.

Rounds a number to the given precision (default 0). The method parameter accepts the following values:

  • common(default): Rounds up or down.
  • ceil: always rounds up.
  • floor: always rounds down.

Filters that modify in iterables

Iterables are lists, tuples, strings, and dictionaries.

Filters that select a single item from iterables

attr(Object, name)
Parameters: Any object, String name
Output: the value of the named attribute of the given object.
Gets an attribute of an object. foo | attr("bar") works like foo.bar. Unlike accessing attributes with ., the attr filter doesn't search for an item if the attribute doesn't exist. You can use it on the available data types to get their properties and methods. It can't get dictionary values by key, or list, tuple, or string items by index.

first(Iterable)
Parameters: Iterable value
Output: Any the first item of the iterable.
Equivalent to myIterable[0]. For a dictionary, it returns the first key.

last(Iterable)
Parameters: Iterable value
Output: Any the last item of the iterable.
Equivalent to myIterable[myIterable | length - 1]. For a dictionary, it returns the last key.

random(Iterable)
Parameters: Iterable
Output: Any a random item of the iterable.
For a dictionary, it returns a random key.

Filters that modify the content of iterables

batch( value, batchSize, dos fill_with=None)
Input: Iterable value, Integer batchsize, Any fill_with
Output: the items of the iterable grouped into batches of the given size.
Returns a list of lists with the given number of items each. It works like slice (see below), but you specify the size of the batches instead of the number of batches. If you provide fill_with, it's used to fill up missing items in the last batch.

{# initialise myList #}
{% set myList = [1, 2, 3, 4, 5] %}
{# output myList filtered by batch with parameters 2 and 999 #} 
{{ myList | batch(2, fill_with=999) | list }} 
Output: [ [1, 2], [3, 4], [5, 999] ]

slice(value, slices, fill_with=None)
Parameters: Iterable value, Integer slices Number of slices, Optional Any fill_with any value
Output: the iterable sliced into the given number of lists, with gaps filled with fill_with.
Returns a list of lists containing the items. It works like batch, but you specify the number of slices instead of the size of the batches. If you provide fill_with, it's used to fill missing values in the last slice.

{# initialise myList #}
{% set myList = [1, 2, 3, 4, 5] %}
{# print the value of myList filtered by slice with parameters 2 and 999 #}
{{ myList | slice(2, fill_with=999) | list }} 
Output: [ [1, 2, 3], [4, 5, 999] ]

map( attribute=attributeName)
Parameters: String attribute attribute name
Output: Any the value of the given attribute for each item in the list.
Looks up an attribute for each item in a list. This is useful for lists of objects when you only need a certain value. You can also use map to apply a filter to each item.

{# set myDictList to a list of dictionaries #} 
{% set myDictList = [ {'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6} ] %}
{# output the attribute a of values from myDictList #}
{{ myDictList | map(attribute='a') | list }} 
Output: [1, 3, 5]

Filters that generate subsets from iterables

map(filter)
Parameters: Filter any of the filter
Output: Any the values of the list, each processed by the given filter.
Applies a filter to each item of a sequence. You need map to apply a filter to every member of a list. For example, if you applied the upper filter to a list without map, it would convert the list to a string and then uppercase the string. You can also us map to look up an attribute. For that, see map(attribute).

reject(test, *testArgs)
Paremeters: Test any test, Args arguments for the test
Output: Iterable the items that fail the given test.
Applies a test to each item and rejects the items where the test succeeds. If you don't specify a test, each item is evaluated as a boolean.

{# initialise myList #}
{% set myList = [1,3,4,9,16, 48] %}
{# print the values from myList not divisible by 3 #}
{{ myList | reject("divisibleby", 3) | list }} 
Output: [1, 4, 16]

rejectattr(attribute, test, *testArgs)
Parameters: String attribute, Test any test, testArgs the arguments for the test
Output: the iterable without the items whose attribute succeeds the test.
Applies a test to the specified attribute of each item and rejects the items where the test succeeds. If you don't specify a test, the attribute's value is evaluated as a boolean.

{# initialise myDict #}
{% set myDict = ({'a': 0}, {'a': 1}, {'a': 2}) %}
{# output myDict without the items where the key 'a' equals 1 #}
{{ myDict | rejectattr('a', 'equalto', 1) | list }} 

Output: [{'a': 0}, {'a': 2}]

select(test, *testArgs)
Paremeters: Test any test, Args arguments for the test
Output: Iterable the items that succeed the given test.
The opposite of reject. Applies a test to each item and selects only the items where the test succeeds. If you don't specify a test, each item is evaluated as a boolean.

{# initialise myTuple #}
{% set myTuple = (1, 2, 3, 4, 5) %}
{# output the values from myTuple that equal 3 as a list #} 
{{ myTuple | select('equalto', 3) | list }} 

Output: [3]

selectattr(attribute, test, *testArgs)
Parameters: String attribute, Test any test, testArgs the arguments for the test
Output: the iterable with only the items whose attribute succeeds the test.
Applies a test to the specified attribute of each item and selects only the items where the test succeeds. If you don't specify a test, the attribute's value is evaluated as a boolean.

{# initialise myDict #} 
{% set myDict = ({'a': 0}, {'a': 1}, {'b': 2}) %}
{# output only the items that have the attribute a, and where a equals 1 #}
{{ myDict | selectattr('a', 'equalto', 1) | list }} 
Output: [{'a': 1}]

unique(value)
Parameters: Iterable any iterable
Output: the unique items of the iterable.
Returns a list of unique items in the order of their first occurrence.

Filters that modify the order of iterables

reverse(value)
Parameters: Iterable any iterable
Output: the iterable with the item order reversed, or an iterator that goes from the last item to the first.

shuffle(value)
Parameters: Iterable any iterable
Output: the iterable in random order.
For tuples, it returns a shuffled list. For dictionaries, it returns a shuffled list of keys.

sort(value, reverse=False, case_sensitive=False, attribute=None)
Parameters: Iterable any iterable, Optional Boolean case_sensitive, String attribute
Output: the iterable sorted in ascending order.
Sorts in ascending order by default. Set reverse=True to sort in descending order. For iterables of strings, use case_sensitive to control case sensitivity. To sort by an attribute (for example, the date of an object), use attribute.

Data type filters

Use these filters to change data types.

Filters that cast variables to different data type

float(value, default=0.0)
Parameters: Any value, Optional Float default the default value
Output: the input value cast to a float.
Converts the value into a floating-point number. If the conversion fails, it returns 0.0. Use default to override this. You can also create inf, -inf, and nan values by applying the float filter to inf, inf, and nan.

int(value, default=0, base=10)
Parameters: Any value, Optional Integer default, Optional Integer base.
Output: the input value as an integer.
Converts the value into an integer. If the conversion fails, it returns 0. Use default to override this. Use base to specify the base of the supplied value, which handles prefixes such as 0b, 0o, and 0x for bases 2, 8, and 16. The base is ignored for decimal numbers and non-string values.

{# initialise x to the binary value 100 #}
{% set x = "0b100" %}
{# convert x from base 2 to base 10 #}
{{ x | int(base=2) }}
Output: 4

string(value)
Parameters Any value.
Output: the input value converted to a Unicode string.
Converts a value to a Unicode string if it isn't one already. Markup strings aren't converted back to Unicode.

list(value)
Parameters: Iterable any iterable
Output: the input iterable as a list.
Converts an iterable into a list. Strings become a list of characters, and dictionaries become a list of keys. The filter doesn't wrap items in a list: {'a': 1} | list != [{'a': 1}] but {'a':1} | list == ['a']

safe(value)
Parameters: Any value
Output: the input value marked as safe.
Marks the value as safe, so it isn't escaped in environments with automatic escaping. Jinja doesn't support automatic escaping here, so you don't need to mark items as safe.

Filters that transform data between different types

default(value, default_value='', boolean=False) or d()
Parameters: Any value, Any default_value, Boolean indicating whether None and empty string count as undefined
Output: the input value if it's defined, otherwise the default value.
If the value is undefined, it returns the default value. Otherwise, it returns the value. To also use the default for variables that evaluate to false (such as None or an empty string), set boolean to true.

dictsort(value, case_sensitive=False, by='key')
Parameters: Dict dictionary, Boolean case_sensisitve, String by, Boolean reverse
Output: the dictionary sorted by key or value, as a list of pairs.
Python dictionaries are unsorted, so use this filter to order them. It returns a list of (key, value) tuples. The by argument can be key or value.

filesizeformat(value, binary=False)
Parameters: Number value, Boolean binary
Output: the input value as a human-readable file size.
Formats the value as a file size string, such as 13 kB, 4.1 MB, or 102 Bytes. By default, it uses decimal prefixes (Mega 10⁶, Giga 10⁹, and so on). If you set binary to true, it uses binary prefixes (Mebi 2²⁰, Gibi 2³⁰, and so on).

from_json(value)
Parameters: JSON String value,
Output: a dictionary that represents the input JSON.
Converts a JSON string into a dictionary that reflects the JSON structure. It also makes these conversions:

  • null becomes none.
  • Booleans become true and false.
  • Strings in double quotes become Unicode strings.

join(value, d='', attribute=None)
Parameters: Iterable any iterable, String d separator, String attribute.
Output: a string that concatenates the items of the iterable.
The separator is an empty string by default. Use d to define it. You can also join a certain attribute of objects. For example, {{ users|join(', ', attribute='username') }} outputs the users joined by username.

json(value)
Parameters: Any value
Output: the JSON representation of the input value as a string.
Makes the following conversions:

  • Tuples become arrays.
  • None becomes null.
  • Functions (macros, filters, tests) and methods become null.
  • All keys become strings in double quotes. Number keys, such as 12, become "12". Boolean keys, such as true, become "true". None keys become null first, and then "null".

In Jinja, true and false are interchangeable with 1 and 0. However, the json filter turns true and false into booleans, and 1 and 0 into numbers.

length(object) or count()
Parameters: Iterable any iterable.
Output: the number of items in the iterable, as an integer.

sum(iterable, attribute=None, start=0)
Parameters: Iterable any iterable, Optional String attribute, Optional Integer start
Output: the sum of a sequence of numbers plus start.
If the sequence is empty, it returns start. To sum only a certain attribute, use attribute, for example,{{ items|sum(attribute='price') }}.

wordcount(String)
Parameters: String value
Output: the number of words in the string.
Words are characters separated by whitespace.

xmlattr( Dictionary, autospace=True)
Parameters: Dictionary any dictionary, Boolean autospace
Output: String that represents the SGML/XML attributes.
Creates an SGML/XML attribute string from the items in a dictionary. It automatically escapes all values that are neither none nor undefined.

{# initialise myDict #}
{% set myDict = {'a': 0, 'b': '&lt;cool&gt;'} %}
{# return the XML attribute string from the dictionary #} 
{{ myDict | xmlattr }} 
Output: 'a="0" b="&lt;cool&gt;"'

Date and time processing

from_timestamp(value, [formatter])
Parameters: Number value Unix timestamp, Optional String formatter format string
Output: the Unix timestamp as a datetime object or a human-readable string.
Without a formatter, it converts the Unix timestamp to a datetime object that you can print directly or process further.

{% set a = 1577865600 | from_timestamp %}
{{ a }}
Output: 2020-01-01 08:00:00+00:00
{{ a.year }} {{ a.month }} {{ a.day }}
Output: 2020 1 1
{{ a.hour }} {{ a.minute }} {{ a.second }}
Output: 8 0 0
date {{ a.date() }} time {{ a.time() }}
Output: date 2020-01-01 time 08:00:00

{# 0 is Monday, 2 is Wednesday, 6 is Sunday #}
{{ a.weekday() }}
Output: 2

{# You can also overwrite the year/month/day/hour/minute/second #}
{% set b = a.replace(day=2, hour=16) %}
{{ b }}
Output: 2020-01-02 16:00:00+00:00
{{ b.timestamp() }}
1577980800.0

The optional formatter can be 'US' or 'EU' for common datetime formats, or a custom format string. A format string contains formatting codes (% followed by a character) that are replaced with time values. The table below lists all available codes.

{{ 1579204800 | from_timestamp('US') }}
Output: 01/16/2020, 08:00 PM
{{ 1579204800 | from_timestamp('EU') }}
Output: 16-01-2020, 20:00
{{ 1579204800 | from_timestamp('%A %d of %B %Y') }}
Output: Thursday 16 of January 2020
Code Description Output example
%y Year without century as a zeropadded decimal number. 13
%Y Year with century as a decimal number. 2013
%A Weekday as locale’s full name. Monday
%a Weekday as locale’s abbreviated name. Mon
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 1
%U Week Number of the year (Sunday as the first day of the week) as a zero padded decimal number.

All days in a new year preceding the first Sunday are considered to be in week 0.

39
%W Week number of the year (Monday as the first day of the week) as a decimal number.

All days in a new year preceding the first Monday are considered to be in week 0.

39
%z UTC offset in the form +HHMM or HHMM (empty string if the object is naive). +0100
%S Second as a zeropadded decimal Number. 05
%-S Second as a decimal Number. (Platform specific) 5
%-d Day of the month as a decimal number. (Platform specific) 9
%B Month as locale’s full name. September
%b Month as locale’s abbreviated name. Sep
%-m Month as a decimal Number. (Platform specific) 9
%M Minute as a zeropadded decimal Number. 06
%-M Minute as a decimal Number. (Platform specific) 6
%f Microsecond as a decimal Number, zeropadded on the left. 000000
%p Locale’s equivalent of either AM or PM. AM
%X Locale’s appropriate time representation. 07:06:05
%x Locale’s appropriate date representation. 09/30/13
%c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
%H Hour (24hour clock) as a zeropadded decimal Number. 07
%-H Hour (24hour clock) as a decimal Number. (Platform specific) 7
%-I Hour (12hour clock) as a decimal Number. (Platform specific) 7
%j Day of the year as a zeropadded decimal Number. 273
%-j Day of the year as a decimal Number. (Platform specific) 273
%% A literal '%' character. %
🚧

Important

Jinja filters like {% set variable=(input+offset)|from_timestamp('%w') %} don't always output a number, even if you expect one. In some contexts, the output is a string. To make sure it's handled as a number, convert it with the int filter: {% set variable=(input+offset)|from_timestamp('%w') | int %}.

to_timestamp(datetime_string, [format], [timezone])
Parameters: datetime_string, Optional String format, Optional String timezone
Output: a Unix timestamp (seconds since 1970) as a number.
Parses a date and time string to a Unix timestamp. Optionally, use a format string as described in from_timestamp. It defaults to a smart guess from among common date and time formats. You can also provide a tz DB timezone name to specify the time zone of the string. It defaults to UTC.

{{ '2020-01-20 20:20:20.20' | to_timestamp }}
Output: 1579551620.2
{{ '25/02/2020' | to_timestamp('%d/%m/%Y', timezone='America/New_York') | int }}
Output: 1582606800

Did this page help you?

© Bloomreach, Inc. All rights reserved.