Inconsistent ValueError with timezone offset out of bounds

Inconsistent ValueError with timezone offset out of bounds

时间戳的时区偏移部分必须在 -12 到 +14 小时之间。否则就是无稽之谈。我正在使用 pandas 数据帧中的时间戳字符串字段,我的一些时间戳是无意义的,因为偏移量超出了这个 -12 + 14 小时边界。

一个好的时间戳:

good = '2019-11-11T07:08:09.640-4:00'

错误的时区偏移

bad = '2019-11-19T22:51:34.619000+17:00'

另一个错误的时区偏移:

bad2 = '2019-11-11T07:08:09.640-31:00'

现在,如果我尝试将这些字符串转换为同种格式:

按预期工作:

import dateutil
dateutil.parser.parse(good).isoformat()
'2019-11-11T07:08:09.640000-04:00'

没有按预期工作,returns 时间戳:

dateutil.parser.parse(bad).isoformat()
'2019-11-19T22:51:34.619000+17:00'

按预期工作,我收到一条错误消息(我随后可以在 if else、try、catch 块中使用)

dateutil.parser.parse(bad2).isoformat()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: offset must be a timedelta strictly between -timedelta(hours=24) and timedelta(hours=24).

为什么当 bad2 和 not bad 都超出时区偏移量时我会收到错误消息

这只是 Python 中的时区偏移范围 - 如错误消息中所述,偏移范围最多为 ±24 小时,这与您的发现一致。它与实时区域中的当前最大和最小偏移量无关,除了如果边界确实 not 允许表示所有实时区域这将是一个问题。

没有简单的方法可以让 datetime 或 dateutil 以您想要的方式失败,因为边界不可配置。如果你想检测 +14/-12 之外的偏移量或任何任意限制,你需要检查 utcoffset,像这样:

if not (timedelta(hours=-12) < dt.utcoffset() < timedelta(hours=14)):
    raise ValueError(...)

就是说,除非您知道您的某些字符串具有这种特定的错误模式,否则我不推荐这种做法。您将学习处理日期时间和时区的一件事是,对它们施加任意限制很少是一个好主意,因为某个地方的某个随机国家会决定制定违反您整洁的 "practical" 限制的规则。我什至对 tzinfo 中的 ±24h 偏移量限制持谨慎态度,但这是语言中内置的,并且真正的偏移量至少不太可能很快违反它。