跳到内容

Timezone Name

时区名称验证和序列化模块。

TimeZoneName

基类: str

TimeZoneName 是一个自定义字符串子类,用于验证和序列化时区名称。

TimeZoneName 类使用 IANA 时区数据库进行验证。它支持严格和非严格模式的时区名称验证。

示例:

一些使用 TimeZoneName 类的示例

正常用法:
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
非严格模式:
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]

确定时区提供程序并返回可用的时区。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_extra_types/timezone_name.py
45
46
47
48
49
50
51
52
53
54
55
56
def get_timezones() -> Set[str]:
    """Determine the timezone provider and return available timezones."""
    if _is_available('zoneinfo') and _is_available('tzdata'):  # pragma: no cover
        return _tz_provider_from_zone_info()
    elif _is_available('pytz'):  # pragma: no cover
        if sys.version_info[:2] > (3, 8):
            _warn_about_pytz_usage()
        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"')