CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-babel

Adds i18n/l10n support for Flask applications.

Pending
Overview
Eval results
Files

formatting.mddocs/

Date, Time, and Number Formatting

Locale-aware formatting functions for dates, times, numbers, and currencies with timezone support.

Capabilities

Date and Time Formatting

Format date and time values according to current locale with automatic timezone conversion.

def format_datetime(datetime=None, format=None, rebase=True):
    """
    Format datetime according to current locale.
    
    Parameters:
    - datetime: datetime object (uses current time if None)
    - format: Format string ('short', 'medium', 'long', 'full') or custom Babel format
    - rebase: Whether to convert to user's timezone (default: True)
    
    Returns:
    Formatted datetime string
    """

def format_date(date=None, format=None, rebase=True):
    """
    Format date according to current locale.
    
    Parameters:
    - date: datetime or date object (uses current date if None)
    - format: Format string ('short', 'medium', 'long', 'full') or custom Babel format
    - rebase: Whether to convert to user's timezone for datetime objects (default: True)
    
    Returns:
    Formatted date string
    """

def format_time(time=None, format=None, rebase=True):
    """
    Format time according to current locale.
    
    Parameters:
    - time: datetime object (uses current time if None)
    - format: Format string ('short', 'medium', 'long', 'full') or custom Babel format
    - rebase: Whether to convert to user's timezone (default: True)
    
    Returns:
    Formatted time string
    """

def format_timedelta(datetime_or_timedelta, granularity: str = 'second', add_direction=False, threshold=0.85):
    """
    Format elapsed time from date to now or format timedelta.
    
    Parameters:
    - datetime_or_timedelta: datetime or timedelta object
    - granularity: Granularity level ('year', 'month', 'week', 'day', 'hour', 'minute', 'second')
    - add_direction: Whether to add directional words like 'ago' or 'in'
    - threshold: Threshold for rounding to next unit (0.0-1.0)
    
    Returns:
    Formatted time difference string
    """

Timezone Utilities

Convert between timezones for proper locale handling.

def to_user_timezone(datetime):
    """
    Convert datetime to user's timezone.
    
    Parameters:
    - datetime: datetime object
    
    Returns:
    datetime object in user's timezone
    """

def to_utc(datetime):
    """
    Convert datetime to UTC and remove timezone info.
    
    Parameters:
    - datetime: datetime object
    
    Returns:
    datetime object in UTC without tzinfo
    """

Number Formatting

Format numbers according to current locale.

def format_number(number):
    """
    Format number for current locale.
    
    Parameters:
    - number: Number to format
    
    Returns:
    Formatted number string
    """

def format_decimal(number, format=None):
    """
    Format decimal number for current locale.
    
    Parameters:
    - number: Number to format
    - format: Decimal format pattern (optional)
    
    Returns:
    Formatted decimal string
    """

def format_percent(number, format=None):
    """
    Format percentage for current locale.
    
    Parameters:
    - number: Number to format as percentage (0.25 = 25%)
    - format: Percentage format pattern (optional)
    
    Returns:
    Formatted percentage string
    """

def format_scientific(number, format=None):
    """
    Format number in scientific notation for current locale.
    
    Parameters:
    - number: Number to format
    - format: Scientific format pattern (optional)
    
    Returns:
    Formatted scientific notation string
    """

Currency Formatting

Format currency values with proper locale-specific symbols and positioning.

def format_currency(number, currency, format=None, currency_digits=True, format_type='standard'):
    """
    Format currency for current locale.
    
    Parameters:
    - number: Amount to format
    - currency: Currency code (e.g., 'USD', 'EUR', 'GBP')
    - format: Currency format pattern (optional)
    - currency_digits: Use currency's standard decimal places (default: True)
    - format_type: Currency format type ('standard', 'accounting')
    
    Returns:
    Formatted currency string
    """

Usage Examples

Date and Time Formatting

from datetime import datetime, timedelta
from flask_babel import format_datetime, format_date, format_time, format_timedelta

now = datetime.utcnow()

# Different format styles
short_datetime = format_datetime(now, 'short')     # "12/31/23, 11:59 PM"
medium_datetime = format_datetime(now, 'medium')   # "Dec 31, 2023, 11:59:59 PM"
long_datetime = format_datetime(now, 'long')       # "December 31, 2023 at 11:59:59 PM UTC"

# Date only
date_str = format_date(now, 'medium')              # "Dec 31, 2023"

# Time only  
time_str = format_time(now, 'short')               # "11:59 PM"

# Time differences
past_time = datetime.utcnow() - timedelta(hours=2)
time_ago = format_timedelta(past_time)             # "2 hours ago"

delta = timedelta(days=3, hours=4)
duration = format_timedelta(delta)                 # "3 days"

Custom Date Formats

from flask_babel import format_datetime

# Custom Babel format patterns
custom_format = format_datetime(now, "yyyy-MM-dd HH:mm")  # "2023-12-31 23:59"
verbose_format = format_datetime(now, "EEEE, MMMM d, yyyy") # "Sunday, December 31, 2023"

Number Formatting

from flask_babel import format_number, format_decimal, format_percent, format_scientific

# Numbers
large_number = 1234567.89
formatted = format_number(large_number)           # "1,234,567.89" (en) or "1.234.567,89" (de)

# Decimals with custom precision
decimal_str = format_decimal(123.456, "#.##")     # "123.46"

# Percentages
percentage = format_percent(0.1575)               # "15.75%" (en) or "15,75 %" (de)

# Scientific notation
scientific = format_scientific(1234567)           # "1.234567E6"

Currency Formatting

from flask_babel import format_currency

amount = 1234.56

# Different currencies
usd = format_currency(amount, 'USD')               # "$1,234.56" (en) or "1.234,56 $" (de)
eur = format_currency(amount, 'EUR')               # "€1,234.56" (en) or "1.234,56 €" (de)
gbp = format_currency(amount, 'GBP')               # "£1,234.56" (en)

# Accounting format (parentheses for negative)
negative_amount = -1234.56
accounting = format_currency(negative_amount, 'USD', format_type='accounting')  # "($1,234.56)"

Timezone Handling

from datetime import datetime
from pytz import timezone
from flask_babel import to_user_timezone, to_utc, format_datetime

# Create UTC datetime
utc_time = datetime.utcnow()

# Convert to user timezone (based on current request context)
user_time = to_user_timezone(utc_time)

# Format in user's timezone
formatted = format_datetime(user_time)

# Convert back to UTC
utc_again = to_utc(user_time)

Jinja2 Template Integration

Flask-Babel automatically provides template filters:

<!-- Date formatting -->
<p>Created: {{ post.created_at|datetimeformat('medium') }}</p>
<p>Date: {{ post.created_at|dateformat('short') }}</p>
<p>Time: {{ post.created_at|timeformat }}</p>

<!-- Number formatting -->
<p>Price: {{ product.price|currencyformat('USD') }}</p>
<p>Discount: {{ discount|percentformat }}</p>
<p>Views: {{ view_count|numberformat }}</p>

<!-- Time differences -->
<p>Posted {{ post.created_at|timedeltaformat }} ago</p>

Install with Tessl CLI

npx tessl i tessl/pypi-flask-babel

docs

configuration.md

formatting.md

index.md

translation.md

tile.json