CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-babel

Internationalization utilities for Python providing locale data, date/time/number formatting, and message catalog management

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

date-time-formatting.mddocs/

Date and Time Formatting

Comprehensive date, time, and datetime formatting with locale-aware patterns, timezone support, and flexible formatting options. Babel's date formatting leverages CLDR data to provide culturally appropriate date and time representations for different locales.

Capabilities

Date Formatting

Format date objects according to locale-specific patterns and conventions.

def format_date(date, format='medium', locale=None):
    """
    Format a date according to locale conventions.
    
    Args:
        date (datetime.date): Date object to format
        format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern
        locale (Locale|str): Target locale
        
    Returns:
        str: Formatted date string
    """

Usage example:

from babel.dates import format_date
from babel import Locale
import datetime

date = datetime.date(2023, 12, 25)
us_locale = Locale('en_US')
fr_locale = Locale('fr_FR')

# Different format lengths
print(format_date(date, format='full', locale=us_locale))    # "Monday, December 25, 2023"
print(format_date(date, format='long', locale=us_locale))    # "December 25, 2023"
print(format_date(date, format='medium', locale=us_locale))  # "Dec 25, 2023"
print(format_date(date, format='short', locale=us_locale))   # "12/25/23"

# French locale
print(format_date(date, format='full', locale=fr_locale))    # "lundi 25 décembre 2023"

Time Formatting

Format time objects with locale-appropriate formatting and timezone support.

def format_time(time, format='medium', tzinfo=None, locale=None):
    """
    Format a time according to locale conventions.
    
    Args:
        time (datetime.time): Time object to format
        format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern
        tzinfo (datetime.tzinfo, optional): Timezone info
        locale (Locale|str): Target locale
        
    Returns:
        str: Formatted time string
    """

Usage example:

from babel.dates import format_time
import datetime

time = datetime.time(14, 30, 45)

print(format_time(time, format='full'))    # "2:30:45 PM"
print(format_time(time, format='short'))   # "2:30 PM"

DateTime Formatting

Format datetime objects with combined date and time formatting.

def format_datetime(datetime, format='medium', tzinfo=None, locale=None):
    """
    Format a datetime according to locale conventions.
    
    Args:
        datetime (datetime.datetime): Datetime object to format
        format (str): Format type ('full', 'long', 'medium', 'short') or custom pattern
        tzinfo (datetime.tzinfo, optional): Timezone info
        locale (Locale|str): Target locale
        
    Returns:
        str: Formatted datetime string
    """

Usage example:

from babel.dates import format_datetime
import datetime

dt = datetime.datetime(2023, 12, 25, 14, 30, 45)

print(format_datetime(dt, format='full'))    # "Monday, December 25, 2023 at 2:30:45 PM"
print(format_datetime(dt, format='short'))   # "12/25/23, 2:30 PM"

Skeleton-Based Formatting

Flexible date formatting using skeleton patterns that adapt to locale conventions.

def format_skeleton(skeleton, datetime, tzinfo=None, fuzzy=True, locale=None):
    """
    Format using flexible date skeleton patterns.
    
    Args:
        skeleton (str): Skeleton pattern (e.g. 'yMMMd', 'Hms')
        datetime (datetime.datetime): Datetime to format
        tzinfo (datetime.tzinfo, optional): Timezone info
        fuzzy (bool): Whether to allow fuzzy matching
        locale (Locale|str): Target locale
        
    Returns:
        str: Formatted string using best available pattern for skeleton
    """

Usage example:

from babel.dates import format_skeleton
import datetime

dt = datetime.datetime(2023, 12, 25, 14, 30)

# Year-Month-Day skeleton
print(format_skeleton('yMMMd', dt))  # "Dec 25, 2023"

# Hour-Minute-Second skeleton  
print(format_skeleton('Hms', dt))    # "14:30:00"

Relative Time Formatting

Format time differences in human-readable relative format.

def format_timedelta(delta, granularity='second', threshold=0.85, add_direction=False, format='long', locale=None):
    """
    Format a timedelta in human-readable relative form.
    
    Args:
        delta (datetime.timedelta): Time difference to format
        granularity (str): Smallest unit to display ('year', 'month', 'week', 'day', 'hour', 'minute', 'second')
        threshold (float): Threshold for using larger units (0-1)
        add_direction (bool): Whether to add direction words ('in', 'ago')
        format (str): Format style ('long', 'short', 'narrow')
        locale (Locale|str): Target locale
        
    Returns:
        str: Human-readable time difference
    """

Usage example:

from babel.dates import format_timedelta
import datetime

# Different time deltas
delta1 = datetime.timedelta(days=2)
delta2 = datetime.timedelta(hours=3, minutes=30)
delta3 = datetime.timedelta(seconds=45)

print(format_timedelta(delta1))                              # "2 days"
print(format_timedelta(delta2, granularity='minute'))        # "3 hours"
print(format_timedelta(delta3, add_direction=True))          # "in 45 seconds"

Interval Formatting

Format intervals between two datetime objects.

def format_interval(start, end, skeleton=None, tzinfo=None, fuzzy=True, locale=None):
    """
    Format an interval between two datetimes.
    
    Args:
        start (datetime.datetime): Start of interval
        end (datetime.datetime): End of interval  
        skeleton (str, optional): Skeleton pattern for formatting
        tzinfo (datetime.tzinfo, optional): Timezone info
        fuzzy (bool): Whether to allow fuzzy matching
        locale (Locale|str): Target locale
        
    Returns:
        str: Formatted interval string
    """

Usage example:

from babel.dates import format_interval
import datetime

start = datetime.datetime(2023, 12, 25, 9, 0)
end = datetime.datetime(2023, 12, 25, 17, 30)

print(format_interval(start, end))  # "Dec 25, 2023, 9:00 AM – 5:30 PM"

Format Pattern Access

Get locale-specific format patterns for different date/time components.

def get_date_format(format='medium', locale=default_locale()):
    """
    Get date format pattern for locale.
    
    Args:
        format (str): Format type ('full', 'long', 'medium', 'short')
        locale (Locale|str): Target locale
        
    Returns:
        DateTimePattern: Date format pattern object
    """

def get_time_format(format='medium', locale=default_locale()):
    """
    Get time format pattern for locale.
    
    Args:
        format (str): Format type ('full', 'long', 'medium', 'short')
        locale (Locale|str): Target locale
        
    Returns:
        DateTimePattern: Time format pattern object
    """

def get_datetime_format(format='medium', locale=default_locale()):
    """
    Get datetime format pattern for locale.
    
    Args:
        format (str): Format type ('full', 'long', 'medium', 'short')
        locale (Locale|str): Target locale
        
    Returns:
        DateTimePattern: Datetime format pattern object
    """

Display Name Access

Get localized names for date/time components.

def get_period_names(width='wide', context='format', locale=default_locale()):
    """
    Get AM/PM period names.
    
    Args:
        width (str): Width ('wide', 'abbreviated', 'narrow')
        context (str): Context ('format', 'stand-alone')
        locale (Locale|str): Target locale
        
    Returns:
        dict: Period names mapping
    """

def get_day_names(width='wide', context='format', locale=default_locale()):
    """
    Get day names (Monday, Tuesday, etc.).
    
    Args:
        width (str): Width ('wide', 'abbreviated', 'narrow')
        context (str): Context ('format', 'stand-alone')
        locale (Locale|str): Target locale
        
    Returns:
        dict: Day names mapping (0=Monday, 6=Sunday)
    """

def get_month_names(width='wide', context='format', locale=default_locale()):
    """
    Get month names.
    
    Args:
        width (str): Width ('wide', 'abbreviated', 'narrow')
        context (str): Context ('format', 'stand-alone')
        locale (Locale|str): Target locale
        
    Returns:
        dict: Month names mapping (1=January, 12=December)
    """

def get_quarter_names(width='wide', context='format', locale=default_locale()):
    """
    Get quarter names (Q1, Q2, etc.).
    
    Args:
        width (str): Width ('wide', 'abbreviated', 'narrow')
        context (str): Context ('format', 'stand-alone')  
        locale (Locale|str): Target locale
        
    Returns:
        dict: Quarter names mapping (1=Q1, 4=Q4)
    """

def get_era_names(width='wide', locale=default_locale()):
    """
    Get era names (BC, AD, etc.).
    
    Args:
        width (str): Width ('wide', 'abbreviated', 'narrow')
        locale (Locale|str): Target locale
        
    Returns:
        dict: Era names mapping
    """

Timezone Support

Timezone handling and display functions.

def get_timezone(zone):
    """
    Get timezone object by identifier.
    
    Args:
        zone (str|datetime.tzinfo|None): Timezone identifier or object
        
    Returns:
        datetime.tzinfo: Timezone object
    """

def get_timezone_name(dt_or_tzinfo, width='long', uncommon=False, locale=default_locale()):
    """
    Get timezone display name.
    
    Args:
        dt_or_tzinfo (datetime.datetime|datetime.tzinfo): Datetime or timezone
        width (str): Width ('long', 'short')
        uncommon (bool): Whether to include uncommon timezones
        locale (Locale|str): Target locale
        
    Returns:
        str: Timezone display name
    """

def get_timezone_location(dt_or_tzinfo, locale=default_locale()):
    """
    Get timezone location name.
    
    Args:
        dt_or_tzinfo (datetime.datetime|datetime.tzinfo): Datetime or timezone
        locale (Locale|str): Target locale
        
    Returns:
        str: Location-based timezone name
    """

def get_timezone_gmt(datetime, width='long', locale=default_locale()):
    """
    Get GMT offset format for timezone.
    
    Args:
        datetime (datetime.datetime): Datetime with timezone
        width (str): Width ('long', 'short')
        locale (Locale|str): Target locale
        
    Returns:
        str: GMT offset string (e.g. "GMT-05:00")
    """

Date/Time Parsing

Parse date and time strings according to locale conventions.

def parse_date(string, locale=default_locale()):
    """
    Parse a date string according to locale.
    
    Args:
        string (str): Date string to parse
        locale (Locale|str): Source locale
        
    Returns:
        datetime.date: Parsed date object
        
    Raises:
        ParseError: If parsing fails
    """

def parse_time(string, locale=default_locale()):
    """
    Parse a time string according to locale.
    
    Args:
        string (str): Time string to parse
        locale (Locale|str): Source locale
        
    Returns:
        datetime.time: Parsed time object
        
    Raises:
        ParseError: If parsing fails
    """

def parse_pattern(pattern):
    """
    Parse a date/time format pattern.
    
    Args:
        pattern (str): Format pattern string
        
    Returns:
        DateTimePattern: Parsed pattern object
    """

Pattern and Format Classes

class DateTimePattern:
    """Represents a parsed date/time format pattern."""
    
    def format(self, datetime, tzinfo=None):
        """
        Format a datetime using this pattern.
        
        Args:
            datetime (datetime.datetime): Datetime to format
            tzinfo (datetime.tzinfo, optional): Timezone info
            
        Returns:
            str: Formatted string
        """

class DateTimeFormat:
    """Formatter for date/time values using patterns."""
    
    def __init__(self, pattern, locale):
        """
        Initialize formatter with pattern and locale.
        
        Args:
            pattern (str|DateTimePattern): Format pattern
            locale (Locale|str): Target locale
        """

Constants

UTC: datetime.tzinfo
    """UTC timezone object"""

LOCALTZ: datetime.tzinfo  
    """Local timezone object"""

Exception Classes

class ParseError(ValueError):
    """Raised when date/time parsing fails."""

Install with Tessl CLI

npx tessl i tessl/pypi-babel

docs

core-locales.md

date-time-formatting.md

index.md

message-catalogs.md

number-currency-formatting.md

plural-language-data.md

units-utilities.md

tile.json