Formatters
These locale-aware formatters helpers can be used in your views as global functions or with the pipe operator. For example, {{ format_date(value, args) }} or {{ value|format_date(args) }}.
1. Format Text
1.1 format_list
A locale-aware version of the join filter.
format_list(
lst: 'Sequence[str]',
*,
style: Literal['standard', 'standard-short', 'or', 'or-short', 'unit', 'unit-short', 'unit-narrow'] = 'standard',
locale: str = 'en'
) -> 'Sequence[str]'
| Argument | Description |
|---|---|
lst |
A sequence of items to format in to a list |
style |
The style to format the list with. |
locale |
Force the locale to use for formatting. |
format_list(['apples', 'oranges', 'pears'], locale='en')
# => 'apples, oranges, and pears'
format_list(['apples', 'oranges', 'pears'], locale='zh')
# => 'apples、oranges和pears'
format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
# => 'omena, peruna tai aplari'
or, as a filter in a template:
{{ ['apples', 'oranges', 'pears'] | format_list(locale='en') }}
{# => 'apples, oranges, and pears' #}
{{ ['apples', 'oranges', 'pears'] | format_list(locale='zh') }}
{# => 'apples、oranges和pears' #}
{{ ['omena', 'peruna', 'aplari'] | format_list(style='or', locale='fi') }}
{# => 'omena, peruna tai aplari' #}
Not all styles are necessarily available in all locales. The function will attempt to fall back to replacement styles according to the rules set forth in the CLDR root XML file, and raise a ValueError if no suitable replacement can be found.
Avaliable styles (from the Unicode TR35-49 spec):
standard- A typical 'and' list for arbitrary placeholders. eg. "January, February, and March"
standard-short- A short version of an 'and' list, suitable for use with short or abbreviated placeholder values. eg. "Jan., Feb., and Mar."
or- A typical 'or' list for arbitrary placeholders. eg. "January, February, or March"
or-short- A short version of an 'or' list. eg. "Jan., Feb., or Mar."
unit- A list suitable for wide units. eg. "3 feet, 7 inches"
unit-short- A list suitable for short units eg. "3 ft, 7 in"
unit-narrow- A list suitable for narrow units, where space on the screen is very limited. eg. "3′ 7″"
Not all styles are necessarily available in all locales.
2. Format Dates
2.1 format_date
Formats a date/datetime according to the current locale and timezone.
format_date(
date: datetime.date | None = None,
format: str = 'medium',
*,
timezone: str | datetime.tzinfo | None = None,
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
date |
The date or datetime object; if None, the current datetimeis used. |
format |
"full", "long", "medium", "short", or a custom date/time pattern. |
timezone |
Force the timezone to use for formatting. |
locale |
Force the locale to use for formatting. |
format_date(date(2007, 4, 1), locale='en_US')
# => 'Apr 1, 2007'
format_date(datetime(2007, 4, 1, 15, 30), locale='en_US')
# => 'Apr 1, 2007, 3:30:00 PM'
You can also specify a custom date pattern:
format_date(date(2007, 4, 1), "EEE, MMM d, ''yy", locale='en')
# => "Sun, Apr 1, '07"
format_date(
datetime(2007, 4, 1, 15, 30),
"yyyy.MM.dd G 'at' HH:mm:ss zzz",
timezone='US/Eastern',
locale='en'
)
# => '2007.04.01 AD at 11:30:00 EDT'
2.2 format_time
Formats a time according to the current locale and timezone.
format_time(
time: datetime.time | datetime.datetime | float | None = None,
format: str = 'medium',
*,
timezone: str | datetime.tzinfo | None = None,
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
time |
The time or datetime object; if None, the currenttime in UTC is used. |
format |
Either "full", "long", "medium", or "short", or a custom date/time pattern. |
timezone |
Force the timezone to use for formatting. |
locale |
Force the locale to use for formatting. |
format_time(time(15, 30), locale='en_US')
# => '3:30:00 PM'
format_time(time(15, 30), format='short', locale='de_DE')
# => '15:30'
You can also specify a custom time pattern:
format_time(time(15, 30), "hh 'o''clock' a", locale='en')
# => "03 o'clock PM"
For any pattern requiring the display of the time-zone a timezone has to be specified explicitly:
dt = datetime(2007, 4, 1, 15, 30).astimezone(get_timezone('Europe/Paris'))
format_time(dt, format='full', timezone='Europe/Paris', locale='fr_FR')
# => '15:30:00 heure d’été d’Europe centrale'
format_time(
dt, "hh 'o''clock' a, zzzz",
timezone='US/Eastern',
locale='en'
)
# => "09 o'clock AM, Eastern Daylight Time"
As that example shows, when this function gets passed a
datetime.datetime value, the actual time in the formatted string is
adjusted to the timezone specified by the timezone parameter. If the
datetime is "naive" (i.e. it has no associated timezone information),
it is assumed to be in UTC.
These timezone calculations are not performed if the value is of type
datetime.time, as without date information there's no way to determine
what a given time would translate to in a different timezone without
information about whether daylight savings time is in effect or not. This
means that time values are left as-is, and the value of the timezone
parameter is only used to display the timezone name if needed:
format_time(
time(15, 30),
format='full',
timezone='Europe/Paris',
locale='fr_FR'
)
# => '15:30:00 heure normale d’Europe centrale'
format_time(
time(15, 30),
format='full',
timezone='US/Eastern',
locale='en_US'
)
# => '3:30:00 PM Eastern Standard Time'
2.3 format_timedelta
Formats a timedelta according to the rules of the given locale.
format_timedelta(
delta: datetime.timedelta | int,
*,
granularity: Literal['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] = 'second',
threshold: float = 0.85,
add_direction: bool = False,
format: Literal['narrow', 'short', 'long'] = 'long',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
delta |
A timedelta object representing the time difference toformat, or the delta in seconds as an int value |
granularity |
Determines the smallest unit that should be displayed, the value can be either "year", "month", "week", "day", "hour", "minute" or "second" |
threshold |
Factor that determines at which point the presentation switches to the next higher unit |
add_direction |
If this flag is set to True, a positive timedelta will meanthe future (eg. in 1 hour) and a negative timedelta the past(eg. 1 hour ago). |
format |
Can be "narrow", "short" or "long". |
locale |
Force the locale to use for formatting. |
format_timedelta(timedelta(weeks=12), locale='en_US')
# => '3 months'
format_timedelta(timedelta(seconds=1), locale='es')
# => '1 segundo'
The granularity parameter can be provided to alter the lowest unit presented, which defaults to a second.
format_timedelta(timedelta(hours=3), granularity='day', locale='en_US')
# => '1 day'
The threshold parameter can be used to determine at which value the presentation switches to the next higher unit. A higher threshold factor means the presentation will switch later. For example:
format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
# => '1 day'
format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
# => '23 hours'
In addition directional information can be provided that informs the user if the date is in the past or in the future:
format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
# => 'in 1 hour'
format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
# => '1 hour ago'
The format parameter controls how compact or wide the presentation is:
format_timedelta(timedelta(hours=3), format='short', locale='en')
# => '3 hr'
format_timedelta(timedelta(hours=3), format='narrow', locale='en')
# => '3h'
2.4 format_skeleton
Formats a datetime according to the given pattern, timezone and locale rules.
format_skeleton(
datetime: datetime.datetime | None = None,
skeleton: str = 'yMMMd',
*,
fuzzy: bool = True,
timezone: str | datetime.tzinfo | None = None,
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
datetime |
The datetime object; if None, the current datetime in UTC is used. |
skeleton |
A date time skeleton as defined in the cldr data. |
fuzzy |
If the skeleton is not found, allow choosing a skeleton that's close enough to it. If there is no close match, a KeyError is thrown. |
timezone |
Force the timezone to use for formatting. |
locale |
Force the locale to use for formatting. |
The skeletons are defined in the CLDR data and provide more flexibility than the simple short/long/medium formats, but are a bit harder to use. The are defined using the date/time symbols without order or punctuation and map to a suitable format for the given locale.
t = datetime(2007, 4, 1, 15, 30)
format_skeleton(t, 'MMMEd', locale='fr')
# => 'dim. 1 avr.'
format_skeleton(t, 'MMMEd', locale='en')
# => 'Sun, Apr 1'
# yMMd is not in the Finnish locale; yMd gets used
format_skeleton(t, 'yMMd', locale='fi')
# => '1.4.2007'
# yMMd is not in the Finnish locale, an error is thrown
format_skeleton(t, 'yMMd', fuzzy=False, locale='fi')
Traceback (most recent call last):
...
KeyError: yMMd
# GH is not in the Finnish locale and there is no close match,
# an error is thrown
format_skeleton(t, 'GH', fuzzy=True, locale='fi_FI')
Traceback (most recent call last):
...
KeyError: None
2.5 format_interval
Formats an interval between two dates or times according to the timezone and locale's rules.
format_interval(
start: datetime.date | datetime.time | float,
end: datetime.date | datetime.time | float,
skeleton: str | None = None,
*,
fuzzy: bool = True,
timezone: str | datetime.tzinfo | None = None,
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
start |
First instant (datetime/date/time) |
end |
Second instant (datetime/date/time) |
skeleton |
The "skeleton format" to use for formatting. |
fuzzy |
If the skeleton is not found, allow choosing a skeleton that's close enough to it. |
timezone |
Force the timezone to use for formatting, if none is already attached. |
locale |
Force the locale to use for formatting. |
format_interval(time(5, 12), time(16, 24), "Hm", locale="en_GB")
# => '5:12–16:24'
format_interval(time(5, 12), time(16, 24), "hm", locale="en_US")
# => '5:12 AM – 4:24 PM'
format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
# => '15.–17.1.2016'
If the start instant equals the end instant, the interval is formatted like the instant.
format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
# => '16:18'
Unknown skeletons fall back to "default" formatting.
format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
# => '2015/01/01~2017/01/01'
format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
# => '15.01.2016 – 17.01.2016'
3. Format Numbers
For these helpers, the number formatted can be an integer, a float, a string, or a Decimal.
3.1 format_size
Format a byte count as a human-readable string with binary (1024) units.
format_size(
number: str | int | float | decimal.Decimal | None,
*,
precision: int = 3,
significant: bool = True,
strip_zeros: bool = True,
round_mode: str = 'default',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
the byte count to format. |
precision |
the number of significant digits to include. |
significant |
If True, precision is the number of significant digits.If False, it's the number of fractional digits (defaults to True). |
strip_zeros |
whether to remove trailing zeros after the decimal point. |
round_mode |
how to round the number; must be one of ["up", "down", "half_up", "half_down", "half_even", "ceiling, "floor, "default"]. |
locale |
force the locale to use for formatting. |
format_size(120)
# => '120 Bytes'
format_size(1024)
# => '1 KB'
format_size(15_678)
# => '15.3 KB'
format_size(133_235_678)
# => '127 MB'
format_size(133_235_678, precision=5)
# => '127.06 MB'
format_size(133_235_678, precision=5, locale="de")
# => '127,06 MB'
3.2 format_decimal
Formats a number for a specific locale.
format_decimal(
number: float | decimal.Decimal | str,
*,
quantization: bool = True,
group_separator: bool = True,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
the number to format. |
quantization |
truncate and round high-precision numbers to the format pattern. Defaults to True. |
group_separator |
boolean to switch group separator on/off in a locale's number format. |
numbering_system |
the numbering system used for formatting number symbols. Defaults to "latn". the special value "default" will use the default numbering system of the locale. |
locale |
force the locale to use for formatting. |
format_decimal(12345.5, locale='en_US')
# => '12,345.5'
format_decimal(1.2345, locale='de')
# => '1,234'
You can also switch the group separator off:
format_decimal(12345.67, locale='fr_CA', group_separator=False)
# => '12345,67'
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the quantization parameter:
format_decimal(1.2346, locale='en_US')
# => '1.235'
format_decimal(1.2346, locale='en_US', quantization=False)
# => '1.2346'
Raises:
- If the numbering system is not supported by the locale.
3.3 format_compact_decimal
Like format_decimal but in compact form.
format_compact_decimal(
number: float | decimal.Decimal | str,
*,
format_type: Literal['short', 'long'] = 'short',
fraction_digits: int = 0,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
the number to format. |
format_type |
compact format to use ("short" or "long"). |
fraction_digits |
number of digits after the decimal point to use. Defaults to 0. |
numbering_system |
the numbering system used for formatting number symbols. Defaults to "latn". the special value "default" will use the default numbering system of the locale. |
locale |
force the locale to use for formatting. |
format_compact_decimal(12_345, format_type="short", locale='en_US')
# => '12K'
format_compact_decimal(12_345, format_type="long", locale='en_US')
# => '12 thousand'
format_compact_decimal(12_345, format_type="short", locale='en_US', fraction_digits=2)
# => '12.34K'
format_compact_decimal(1_234_567, format_type="short", locale="ja_JP")
# => '123万'
format_compact_decimal(2_345_678, format_type="long", locale="mk")
# => '2 милиони'
format_compact_decimal(21_000_000, format_type="long", locale="mk")
# => '21 милион'
format_compact_decimal(12_345, format_type="short", locale='ar_EG', fraction_digits=2, numbering_system='default')
# => '12٫34 ألف'
Raises:
- If the numbering system is not supported by the locale.
3.4 format_currency
Formats a number (as a float, Decimal, or string) as a currency value, following the locale's formatting rules.
format_currency(
number: float | decimal.Decimal | str,
currency: str,
*,
format: str | None = None,
currency_digits: bool = True,
format_type: Literal['name', 'standard', 'accounting'] = 'standard',
quantization: bool = True,
group_separator: bool = True,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
The number to format. |
currency |
The currency code. |
format |
The format string to use. |
format_type |
The currency format type to use. Can be "name", "standard" or "accounting". Defaults to "standard". |
currency_digits |
Use the currency's natural number of decimal digits or not. Defaults to True. |
quantization |
Truncate and round high-precision numbers to the format pattern. Defaults to True. |
group_separator |
Boolean to switch group separator on/off in a locale's number format. |
numbering_system |
The numbering system used for formatting number symbols. Defaults to "latn". The special value "default" will use the default numbering system of the locale. |
locale |
Force the locale to use for formatting. |
format_currency(1_099.98, 'USD', locale='en_US')
# => '$1,099.98'
format_currency(1_099.98, 'USD', locale='es_CO')
# => 'US$1.099,98'
format_currency(1_099.98, 'EUR', locale='de_DE')
# => '1.099,98 €'
format_currency(1_099.98, 'EGP', locale='ar_EG', numbering_system='default')
# => '1٬099٫98 ج.م.'
The format can also be specified explicitly. The currency is placed with the '¤' sign. As the sign gets repeated the format expands (¤ being the symbol, ¤¤ is the currency abbreviation and ¤¤¤ is the full name of the currency):
format_currency(1_099.98, 'EUR', format='¤¤ #,##0.00', locale='en_US')
# => 'EUR 1,099.98'
format_currency(1_099.98, 'EUR', format='#,##0.00 ¤¤¤', locale='en_US')
# => '1,099.98 euros'
Currencies usually have a specific number of decimal digits. This function favours that information over the given format:
format_currency(1_099.98, 'JPY', locale='en_US')
# => '¥1,100'
format_currency(1_099.98, 'COP', format='#,##0.00', locale='es_ES')
# => '1.099,98'
However, the number of decimal digits can be overridden from the currency
information, by setting the last parameter to False:
format_currency(1_099.98, 'JPY', locale='en_US', currency_digits=False)
# => '¥1,099.98'
format_currency(1_099.98, 'COP', format='#,##0.00', locale='es_ES', currency_digits=False)
# => '1.099,98'
If a format is not specified the type of currency format to use from the locale can be specified:
format_currency(1_099.98, 'EUR', locale='en_US', format_type='standard')
# => '€1,099.98'
When the given currency format type is not available, an exception is raised:
format_currency('1_099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
You can also switch the group separator off:
format_currency(101_299.98, 'USD', locale='en_US', group_separator=False)
# => '$101299.98'
You can also pass format_type='name' to use long display names. The order of the number and currency name, along with the correct localized plural form of the currency name, is chosen according to locale:
format_currency(1, 'USD', locale='en_US', format_type='name')
# => '1.00 US dollar'
format_currency(1_099.98, 'USD', locale='en_US', format_type='name')
# => '1,099.98 US dollars'
format_currency(1_099.98, 'USD', locale='ee', format_type='name')
# => 'us ga dollar 1,099.98'
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the quantization parameter:
format_currency(1_099.9876, 'USD', locale='en_US')
# => '$1,099.99'
format_currency(1_099.9876, 'USD', locale='en_US', quantization=False)
# => '$1,099.9876'
Raises:
- If the numbering system is not supported by the locale.
3.5 format_compact_currency
Like format_currency but in compact form.
format_compact_currency(
number: float | decimal.Decimal | str,
currency: str,
*,
fraction_digits: int = 0,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
the number to format. |
currency |
the currency code. |
fraction_digits |
number of digits after the decimal point to use. Defaults to 0. |
numbering_system |
the numbering system used for formatting number symbols. Defaults to "latn". the special value "default" will use the default numbering system of the locale. |
locale |
force the locale to use for formatting. |
format_compact_currency(12_345, 'USD', locale='en_US')
# => '$12K'
format_compact_currency(123_456_789, 'USD', locale='en_US', fraction_digits=2)
# => '$123.46M'
format_compact_currency(123_456_789, 'EUR', locale='de_DE', fraction_digits=1)
# => '123,5 Mio. €'
Raises:
- If the numbering system is not supported by the locale.
3.6 format_percent
Return formatted percent value following the locale's formatting rules.
format_percent(
number: float | decimal.Decimal | str,
*,
format: str | None = None,
quantization: bool = True,
group_separator: bool = True,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
The number to format as a percent. |
format |
The format string to use. |
quantization |
Truncate and round high-precision numbers to the format pattern. Defaults to True. |
group_separator |
Boolean to switch group separator on/off in a locale's number format. |
numbering_system |
The numbering system used for formatting number symbols. Defaults to "latn". The special value "default" will use the default numbering system of the locale. |
locale |
Force the locale to use for formatting. |
format_percent(0.34, locale='en_US')
# => '34%'
format_percent(25.1234, locale='en_US')
# => '2,512%'
format_percent(25.1234, locale='sv_SE')
# => '2 512 %'
format_percent(25.1234, locale='ar_EG', numbering_system='default')
# => '2٬512%'
The format pattern can also be specified explicitly:
format_percent(25.1234, format='#,##0‰', locale='en_US')
# => '25,123‰'
And you can switch the group separator off:
format_percent(229_291.1234, locale='pt_BR', group_separator=False)
# => '22929112%'
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the quantization parameter:
format_percent(23.9876, locale='en_US')
# => '2,399%'
format_percent(23.9876, locale='en_US', quantization=False)
# => '2,398.76%'
Raises:
- If the numbering system is not supported by the locale.
3.7 format_scientific
Formats a number in scientific notation following the locale's formatting rules.
format_scientific(
number: float | decimal.Decimal | str,
*,
format: str | None = None,
quantization: bool = True,
numbering_system: str = 'latn',
locale: str = 'en'
) -> str
| Argument | Description |
|---|---|
number |
The number to format in scientific notation. |
format |
The format string to use. |
quantization |
Truncate and round high-precision numbers to the format pattern. Defaults to True. |
numbering_system |
The numbering system used for formatting number symbols. Defaults to "latn". The special value "default" will use the default numbering system of the locale. |
locale |
Force the locale to use for formatting. |
format_scientific(10_000, locale='en_US')
# => '1E4'
format_scientific(10_000, locale='ar_EG', numbering_system='default')
# => '1أس4'
The format pattern can also be specified explicitly:
format_scientific(1_234_567, format='##0.##E00', locale='en_US')
# => '1.23E06'
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the quantization parameter:
format_scientific(1_234.9876, format='#.##E0', locale='en_US')
# => '1.23E3'
format_scientific(1_234.9876, format='#.##E0', locale='en_US', quantization=False)
# => '1.2349876E3'
Raises:
- If the numbering system is not supported by the locale.