Unofficial research mirror of the Pydantic documentation (MIT licence) for an academic study. Some details differ from the official documentation, so do not rely on this site for real projects. Official docs: docs.pydantic.dev. About this study.
Skip to content

Timezone Name

Time zone name validation and serialization module.

TimeZoneName

Bases: str

TimeZoneName is a custom string subclass for validating and serializing timezone names.

The TimeZoneName class uses the IANA Time Zone Database for validation. It supports both strict and non-strict modes for timezone name validation.

Examples:

Some examples of using the TimeZoneName class:

Normal usage:
from pydantic_extra_types.timezone_name import TimeZoneName
from pydantic import BaseModel
class Location(BaseModel):
    city: str
    timezone: TimeZoneName

loc = Location(city="New York", timezone="America/New_York")
print(loc.timezone)

>> America/New_York
Non-strict mode:
from pydantic_extra_types.timezone_name import TimeZoneName, timezone_name_settings

@timezone_name_settings(strict=False)
class TZNonStrict(TimeZoneName):
    pass

tz = TZNonStrict("america/new_york")

print(tz)

>> america/new_york

get_timezones

get_timezones() -> set[str]

Determine the timezone provider and return available timezones.

Source code in .venv/lib/python3.12/site-packages/pydantic_extra_types/timezone_name.py
45
46
47
48
49
50
51
52
53
54
55
56
57
def get_timezones() -> set[str]:
    """Determine the timezone provider and return available timezones."""
    if _is_available('zoneinfo'):  # pragma: no cover
        timezones = _tz_provider_from_zone_info()
        if len(timezones) == 0:  # pragma: no cover
            raise ImportError('No timezone provider found. Please install tzdata with "pip install tzdata"')
        return timezones
    elif _is_available('pytz'):  # pragma: no cover
        return _tz_provider_from_pytz()
    else:  # pragma: no cover
        if sys.version_info[:2] == (3, 8):
            raise ImportError('No pytz module found. Please install it with "pip install pytz"')
        raise ImportError('No timezone provider found. Please install tzdata with "pip install tzdata"')