Python 3.12 zoneinfo 实战:用 UTC 往返识别唯一、重复和不存在的本地时间
给一条用户输入的本地时间加上时区,并不等于它已经对应一个真实且唯一的时刻。本文只解决一个小问题:已知“墙上显示的年月日时分秒”和明确的时区,如何判断它是唯一时间、重复时间,还是根本不存在的时间。实现基于 Python 3.12 的标准库,不读取系统当前时间,不修改任何日历,也不替业务决定遇到夏令时该怎么办。
配图为独立模型生成的概念示意图,图中标有 CONCEPT DIAGRAM;它不是软件截图,也不是对某个城市当下规则的实时展示。
一、先把“字符串格式正确”和“时间真实存在”分开
解析成功只能说明日期字段符合格式。以本次测试使用的 America/New_York 历史数据为例,2024 年 3 月 10 日的本地 02:30 落在跳时缺口里;同年 11 月 3 日的本地 01:30 则出现两次,分别对应 05:30 UTC 和 06:30 UTC。前者没有候选瞬间,后者有两个候选瞬间,不能靠默认值假装问题不存在。
datetime 构造器或 replace(tzinfo=zone) 可以产生带时区的对象,但这一步只是附加解释规则,不是严格有效性校验。尤其不要通过“utcoffset() 能返回一个偏移量”推断该墙上时间确实出现过。另一个易错点是直接对 naive 对象调用 astimezone():它会按系统本地时区解释输入,因此不能替代显式指定输入时区的接口。相关语义见 Python datetime 官方文档。
二、这个小工具的输入与输出契约
输入 wall 必须是 datetime,并且 tzinfo 严格为 None。这里刻意不接受“tzinfo 存在、但 utcoffset() 返回 None”的宽泛 naive 对象,以免调用方混入自定义时区行为。zone 必须是 ZoneInfo 或标准库 datetime.timezone 对象;字符串由上层先转换成 ZoneInfo,不在分类函数里偷偷猜测城市或使用服务器默认时区。
输入 wall 的 fold 被明确忽略:它是待分类的墙上时间,不是已获用户同意的消歧结果。分类器始终测试两个 fold。返回值包含 kind 和不可变候选元组;每个候选同时保留 UTC 瞬间与从 UTC 正向转换回来的本地表示,方便上层展示偏移量和 fold,而不是只给一个无法解释的布尔值。
unique:去重后恰好一个 UTC 候选。
ambiguous:去重后两个 UTC 候选,按 UTC 从早到晚排列。
nonexistent:两个尝试都无法往返还原输入的墙上字段。
这三个状态是时区映射结果,不是提交表单、执行订单或排班的业务许可。一个真实存在的本地时间,也可能因为业务营业时段而不可用,那是独立校验层。
三、核心算法:试两个 fold,再走真正的 UTC 往返
处理每个 fold 时,先附加时区得到暂定对象,将它转为 UTC,再由该 UTC 瞬间转换回原时区。只有回来的年月日时分秒和微秒与输入相同,才保留候选。比较墙上字段时去掉 tzinfo 并归一化 fold,因为我们检验的是这组字段是否有真实映射,而不是强行要求普通时间的 fold=1 也保留为 1。
不能省去中间的 UTC 转换:给同一个时区对象调用 astimezone(zone) 可能直接返回原有表示,无法证明有效性。也不能只比较两个暂定对象的 utcoffset() 是否相同,因为重复区间与缺口都可能产生两个不同偏移量;偏移不同不是“这是重复时间”的充分条件。
最后必须按 UTC 候选去重。普通时段里,fold=0 和 fold=1 通常落到同一个 UTC 瞬间,不去重就会误报 ambiguous。反过来,在重复区间里,两个拥有同一 tzinfo 对象的本地 datetime 可能比较相等,拿本地对象放进 set 又会错误合并。使用 UTC 作为键同时避开这两种错误。fold 及缺口语义来自 PEP 495;下面的实现和测试是针对本教程契约编写的独立示例。
四、完整实现:保存为 local_time.py
"""Classify wall times; never infer the caller's business policy."""
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Literal
from zoneinfo import ZoneInfo
Kind = Literal['unique', 'ambiguous', 'nonexistent']
Policy = Literal['reject', 'earlier', 'later']
@dataclass(frozen=True, slots=True)
class Candidate:
utc: datetime
local: datetime
@dataclass(frozen=True, slots=True)
class LocalResult:
kind: Kind
candidates: tuple[Candidate, ...]
class AmbiguousLocalTime(ValueError):
pass
class NonexistentLocalTime(ValueError):
pass
def classify_local(
wall: datetime, zone: ZoneInfo | timezone
) -> LocalResult:
"""Require tzinfo=None; ignore input fold and classify both folds.
Only ZoneInfo and datetime.timezone are supported. OverflowError
from conversions near datetime limits is intentionally propagated.
"""
if not isinstance(wall, datetime):
raise TypeError('wall must be a datetime')
if wall.tzinfo is not None:
raise ValueError('wall must have tzinfo=None')
if not isinstance(zone, (ZoneInfo, timezone)):
raise TypeError('zone must be ZoneInfo or datetime.timezone')
wall = wall.replace(fold=0)
by_utc: dict[datetime, Candidate] = {}
for fold in (0, 1):
tentative = wall.replace(tzinfo=zone, fold=fold)
utc = tentative.astimezone(timezone.utc)
back = utc.astimezone(zone)
if back.replace(tzinfo=None, fold=0) == wall:
by_utc[utc] = Candidate(utc=utc, local=back)
candidates = tuple(by_utc[key] for key in sorted(by_utc))
kind: Kind = ('nonexistent', 'unique', 'ambiguous')[len(candidates)]
return LocalResult(kind=kind, candidates=candidates)
def resolve_local(
wall: datetime,
zone: ZoneInfo | timezone,
*,
on_ambiguous: Policy,
) -> datetime:
"""Return a UTC instant; the ambiguity policy is mandatory.
Missing wall times always raise. No automatic shift is performed.
"""
if on_ambiguous not in ('reject', 'earlier', 'later'):
raise ValueError('unknown ambiguity policy')
result = classify_local(wall, zone)
if result.kind == 'nonexistent':
raise NonexistentLocalTime('no UTC instant matches this wall time')
if result.kind == 'ambiguous':
if on_ambiguous == 'reject':
raise AmbiguousLocalTime('choose earlier or later explicitly')
index = 0 if on_ambiguous == 'earlier' else -1
return result.candidates[index].utc
return result.candidates[0].utcresolve_local 的 on_ambiguous 是必填的关键字参数,没有默认“较早”或“较晚”。调用方要么明确传入 reject 并处理异常,要么在已决定业务规则后传入 earlier 或 later。它返回 UTC datetime,便于后续按瞬间存储和排序;分类器的候选仍保留本地显示信息。
不存在的时间始终抛出 NonexistentLocalTime,连 earlier 和 later 也不能把它自动挪走。因为“向后顺延一小时”“跳到第一个有效时刻”“跳过这次执行”“退回让用户重填”完全不是同一件事。若业务决定调整输入,应在上层明确产生一个新的墙上时间,再调用分类器校验,必要时保留原始输入和调整原因,而不是把纠错伪装成原始时间。
异常也要分层。ZoneInfoNotFoundError 说明指定时区数据没有找到,可能是键名无效或部署缺少可用数据,并不表示这个日期落在缺口里。它也不能证明某个拼错的名称原本想表示哪座城市。代码不吞掉构造阶段的错误、不自动降级为 UTC,更不会把数据缺失归类成 nonexistent。接近 datetime 年份上下界时,UTC 转换可能溢出;这里保留 OverflowError,让范围问题与时间不存在问题保持区别。
五、35 项确定性测试:边界、策略和两个容易忽略的陷阱
把以下内容保存为同目录下的 test_local_time.py,执行 python -m unittest -v test_local_time。测试只使用固定的历史日期、UTC 和固定偏移,不依赖今天是哪一天,也不依赖机器系统本地时区。缺少 America/New_York 数据时应明确失败并修复部署数据,而不是跳过关键用例后仍宣称校验通过。
春季缺口使用左闭右开边界:02:00 开始不存在,02:59:59.999999 仍不存在,03:00 恢复唯一。秋季重复区间也逐个检查开始、内部和最后一微秒,并确认 02:00 已恢复唯一。其他用例覆盖微秒、输入类型、普通时间去重、跨日固定偏移、必填策略、不可变结果和范围溢出;其中一些测试包含子用例,但 unittest 测试方法总数为 35。
import unittest
from dataclasses import FrozenInstanceError
from datetime import date, datetime, timedelta, timezone, tzinfo
from zoneinfo import ZoneInfo
from local_time import (
AmbiguousLocalTime, NonexistentLocalTime,
classify_local, resolve_local,
)
UTC = timezone.utc
NY = ZoneInfo('America/New_York')
REPEAT = datetime(2024, 11, 3, 1, 30)
GAP = datetime(2024, 3, 10, 2, 30)
class NoneOffset(tzinfo):
def utcoffset(self, dt):
return None
class LocalTimeTests(unittest.TestCase):
def assert_kind(self, wall, kind):
result = classify_local(wall, NY)
self.assertEqual(result.kind, kind)
self.assertEqual(len(result.candidates), {
'unique': 1, 'ambiguous': 2, 'nonexistent': 0,
}[kind])
return result
def test_01_winter_unique(self):
r = self.assert_kind(datetime(2024, 1, 15, 12), 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 1, 15, 17, tzinfo=UTC))
def test_02_summer_unique(self):
r = self.assert_kind(datetime(2024, 7, 15, 12), 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 7, 15, 16, tzinfo=UTC))
def test_03_last_microsecond_before_gap(self):
self.assert_kind(datetime(2024, 3, 10, 1, 59, 59, 999999), 'unique')
def test_04_gap_start_is_missing(self):
self.assert_kind(datetime(2024, 3, 10, 2), 'nonexistent')
def test_05_gap_middle_is_missing(self):
self.assert_kind(GAP, 'nonexistent')
def test_06_gap_last_microsecond_is_missing(self):
self.assert_kind(datetime(2024, 3, 10, 2, 59, 59, 999999), 'nonexistent')
def test_07_gap_end_is_unique(self):
r = self.assert_kind(datetime(2024, 3, 10, 3), 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 3, 10, 7, tzinfo=UTC))
def test_08_before_fold_is_unique(self):
self.assert_kind(datetime(2024, 11, 3, 0, 59, 59, 999999), 'unique')
def test_09_fold_start_is_ambiguous(self):
self.assert_kind(datetime(2024, 11, 3, 1), 'ambiguous')
def test_10_fold_middle_is_ambiguous(self):
self.assert_kind(REPEAT, 'ambiguous')
def test_11_fold_last_microsecond_is_ambiguous(self):
self.assert_kind(datetime(2024, 11, 3, 1, 59, 59, 999999), 'ambiguous')
def test_12_fold_end_is_unique(self):
r = self.assert_kind(datetime(2024, 11, 3, 2), 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 11, 3, 7, tzinfo=UTC))
def test_13_utc_zoneinfo_deduplicates_folds(self):
r = classify_local(REPEAT, ZoneInfo('UTC'))
self.assertEqual((r.kind, len(r.candidates)), ('unique', 1))
self.assertEqual(r.candidates[0].utc, REPEAT.replace(tzinfo=UTC))
def test_14_fixed_positive_fractional_offset(self):
r = classify_local(datetime(2024, 5, 1, 0), timezone(timedelta(hours=5, minutes=45)))
self.assertEqual(r.kind, 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 4, 30, 18, 15, tzinfo=UTC))
def test_15_fixed_negative_fractional_offset(self):
r = classify_local(datetime(2024, 5, 1, 23), timezone(-timedelta(hours=3, minutes=30)))
self.assertEqual(r.kind, 'unique')
self.assertEqual(r.candidates[0].utc, datetime(2024, 5, 2, 2, 30, tzinfo=UTC))
def test_16_seconds_and_microseconds_preserved(self):
wall = REPEAT.replace(second=17, microsecond=456789)
r = classify_local(wall, NY)
for c in r.candidates:
self.assertEqual((c.utc.second, c.utc.microsecond), (17, 456789))
self.assertEqual(c.local.replace(tzinfo=None, fold=0), wall)
def test_17_naive_fold_does_not_select_candidate(self):
self.assertEqual(classify_local(REPEAT.replace(fold=1), NY), classify_local(REPEAT, NY))
def test_18_unique_naive_fold_normalizes_to_zero(self):
r = classify_local(datetime(2024, 1, 1, fold=1), NY)
self.assertEqual((r.kind, r.candidates[0].local.fold), ('unique', 0))
def test_19_date_is_not_datetime(self):
with self.assertRaises(TypeError):
classify_local(date(2024, 1, 1), NY)
def test_20_aware_input_rejected(self):
with self.assertRaises(ValueError):
classify_local(REPEAT.replace(tzinfo=NY), NY)
def test_21_tzinfo_returning_none_rejected(self):
with self.assertRaises(ValueError):
classify_local(REPEAT.replace(tzinfo=NoneOffset()), NY)
def test_22_string_and_custom_zone_rejected(self):
for zone in ('America/New_York', NoneOffset(), None):
with self.subTest(zone=zone), self.assertRaises(TypeError):
classify_local(REPEAT, zone)
def test_23_candidates_are_sorted_distinct_utc_instants(self):
r = classify_local(REPEAT, NY)
self.assertEqual(tuple(c.utc for c in r.candidates), (
datetime(2024, 11, 3, 5, 30, tzinfo=UTC),
datetime(2024, 11, 3, 6, 30, tzinfo=UTC),
))
def test_24_round_trip_retains_correct_fold_and_offsets(self):
a, b = classify_local(REPEAT, NY).candidates
self.assertEqual((a.local.fold, b.local.fold), (0, 1))
self.assertEqual((a.local.utcoffset(), b.local.utcoffset()), (
timedelta(hours=-4), timedelta(hours=-5),
))
def test_25_result_and_candidates_are_frozen(self):
r = classify_local(REPEAT, NY)
self.assertIsInstance(r.candidates, tuple)
with self.assertRaises(FrozenInstanceError):
r.kind = 'unique'
with self.assertRaises(FrozenInstanceError):
r.candidates[0].utc = datetime(2024, 1, 1, tzinfo=UTC)
def test_26_policy_must_be_supplied(self):
with self.assertRaises(TypeError):
resolve_local(REPEAT, NY)
def test_27_unknown_policy_rejected(self):
with self.assertRaises(ValueError):
resolve_local(datetime(2024, 1, 1), NY, on_ambiguous='guess')
def test_28_earlier_policy(self):
self.assertEqual(resolve_local(REPEAT, NY, on_ambiguous='earlier'),
datetime(2024, 11, 3, 5, 30, tzinfo=UTC))
def test_29_later_policy(self):
self.assertEqual(resolve_local(REPEAT, NY, on_ambiguous='later'),
datetime(2024, 11, 3, 6, 30, tzinfo=UTC))
def test_30_reject_policy_and_unique_success(self):
with self.assertRaises(AmbiguousLocalTime):
resolve_local(REPEAT, NY, on_ambiguous='reject')
self.assertEqual(resolve_local(datetime(2024, 1, 15, 12), NY, on_ambiguous='reject'),
datetime(2024, 1, 15, 17, tzinfo=UTC))
def test_31_no_policy_silently_repairs_gap(self):
for policy in ('reject', 'earlier', 'later'):
with self.subTest(policy=policy), self.assertRaises(NonexistentLocalTime):
resolve_local(GAP, NY, on_ambiguous=policy)
def test_32_attaching_zone_does_not_validate(self):
for fold, expected_hour in ((0, 3), (1, 1)):
with self.subTest(fold=fold):
tentative = GAP.replace(tzinfo=NY, fold=fold)
back = tentative.astimezone(UTC).astimezone(NY)
self.assertEqual(back.hour, expected_hour)
self.assertNotEqual(back.replace(tzinfo=None), GAP)
def test_33_wall_arithmetic_differs_from_elapsed_time(self):
start = datetime(2024, 3, 10, 1, 30, tzinfo=NY)
wall_add = start + timedelta(hours=1)
elapsed_add = (start.astimezone(UTC) + timedelta(hours=1)).astimezone(NY)
self.assertEqual(classify_local(wall_add.replace(tzinfo=None), NY).kind, 'nonexistent')
self.assertEqual((elapsed_add.hour, elapsed_add.minute), (3, 30))
def test_34_local_equality_is_not_utc_identity(self):
a, b = classify_local(REPEAT, NY).candidates
self.assertEqual(a.local, b.local)
self.assertEqual(b.local - a.local, timedelta(0))
self.assertNotEqual(a.utc, b.utc)
self.assertEqual(b.utc - a.utc, timedelta(hours=1))
def test_35_datetime_bounds_do_not_become_missing(self):
for wall in (datetime.min, datetime.max):
with self.subTest(wall=wall):
self.assertEqual(classify_local(wall, UTC).kind, 'unique')
for wall, zone in (
(datetime.min, timezone(timedelta(hours=1))),
(datetime.max, timezone(timedelta(hours=-1))),
):
with self.subTest(wall=wall), self.assertRaises(OverflowError):
classify_local(wall, zone)
if __name__ == '__main__':
unittest.main(verbosity=2)六、分类正确之后,仍要选对时间算术
“当地钟表加一小时”和“真实经过一小时”是不同运算。测试 33 从纽约 2024-03-10 01:30 开始:直接给本地 aware datetime 加 timedelta(hours=1),会得到墙上 02:30,这正是应由分类器拒绝的缺口;先转成 UTC、加一小时、再转回纽约,结果才是当地 03:30。测试 34 则证明两个重复的 01:30 本地表示直接相减可以得到零,但它们的 UTC 候选相差一小时。
因此,处理经过时长时通常在 UTC 时间线上运算;处理“每个本地日期固定钟点”时,则逐次构造目标墙上字段并重新分类。后者不能简单用“上次 UTC 加 24 小时”代替。这里不是给所有业务选定一种调度方案,而是要求业务先说明自己究竟约束的是墙上时刻还是经过时长。官方对同一 tzinfo 下比较和相减的说明见 datetime 运算规则。
七、运行记录与时区数据来源
本教程实际运行使用 Python 3.12.14。原始源码运行 35 项测试全部通过;从文章 HTML 中解码出的两段 Python 代码另存到独立目录后,再次运行相同 35 项测试,也全部通过。这是固定测试集的结果,不是对所有历史时区、所有未来规则或任意自定义 tzinfo 实现的穷尽证明。
本次环境的 TZPATH 首项为 /usr/share/zoneinfo,实际存在 America/New_York 和 UTC 对应文件;系统 tzdata.zi 的版本标记为 2026b。环境另安装 tzdata Python 包 2026.5,但不能把已安装包的版本误当成此次系统文件的来源版本。纽约文件的 SHA-256 为 e9ed07d7bee0c76a9d442d091ef1f01668fee7c4f26014c0a868b19fe6c18a95。以上是本次只读检查结果,未安装或更新时区数据,也未改变搜索路径。
ZoneInfo 优先按搜索路径寻找数据,失败后才尝试 tzdata 包;标准库本身不随模块直接提供完整时区库。部署时应记录实际数据来源与版本,而不是只记录 Python 版本,详见 zoneinfo 数据来源文档和 PEP 615。时区数据更新后,既有 ZoneInfo 对象不会被承诺自动变成新规则对象,应按项目的部署流程重建进程或对象,而不是在请求处理中随意改缓存和搜索路径。
文中纽约转换是用于回归的 2024 年固定样本;不据此断言当前或未来的法定时区规则。fold 也不是简单的“是否夏令时”开关,时间偏移变化并非只能是一小时。算法不硬编码一小时差值,真正决定映射的是加载的数据。需要跨环境重现时,应同时保存代码、测试、实际时区数据来源及其版本。
八、一个清晰的职责边界
让输入层负责解析与时区标识,让分类器负责回答有几个真实 UTC 瞬间,让业务层决定重复或缺失时刻怎么处理,让存储层保留最终瞬间以及必要的原始语义。不要把“附加 tzinfo 成功”“fold 有默认值”或“测试当天没有夏令时变化”误当成业务已经消歧。最有价值的结果不是永远返回一个时间,而是在需要人或规则作决定时,可靠地停止猜测。


