这里首先要注意一些事情(如评论):
- Python 内置 strptime 在这里会遇到困难 -
%z 不会解析单个数字偏移小时,%Z 不会解析一些(可能)不明确的时区缩写。
然后,OFX 银行 2.3 版文档(第 3.2.8.2 节日期和日期时间)给我留下了一些问题:
- UTC 偏移量是可选的吗?
- 为什么将 EST 称为时区,而它只是一个缩写词?
- 为什么在示例中 UTC 偏移量是 -5 小时,而在 1996 年 10 月 5 日,美国/东部时间是 UTC-4?
- 指定了分钟的偏移量,例如+5:30 亚洲/加尔各答?
- (有意见)为什么要重新发明轮子,而不是使用 ISO 8601 等常用标准?
无论如何,这是一个自定义解析器的尝试:
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
def parseOFXdatetime(s, tzinfos=None, _tz=None):
"""
parse OFX datetime string to an aware Python datetime object.
"""
# first, treat formats that have no UTC offset specified.
if not '[' in s:
# just make sure default format is satisfied by filling with zeros if needed
s = s.ljust(14, '0') + '.000' if not '.' in s else s
return datetime.strptime(s, "%Y%m%d%H%M%S.%f").replace(tzinfo=timezone.utc)
# offset and tz are specified, so first get the date/time, offset and tzname components
s, off = s.strip(']').split('[')
off, name = off.split(':')
s = s.ljust(14, '0') + '.000' if not '.' in s else s
# if tzinfos are specified, map the tz name:
if tzinfos:
_tz = tzinfos.get(name) # this might still leave _tz as None...
if not _tz: # ...so we derive a tz from a timedelta
_tz = timezone(timedelta(hours=int(off)), name=name)
return datetime.strptime(s, "%Y%m%d%H%M%S.%f").replace(tzinfo=_tz)
# some test strings
t = ["19961005132200.124[-5:EST]", "19961005132200.124", "199610051322", "19961005",
"199610051322[-5:EST]", "19961005[-5:EST]"]
for s in t:
print(# normal parsing
f'{s}\n {repr(parseOFXdatetime(s))}\n'
# parsing with tzinfo mapping supplied; abbreviation -> timezone object
f' {repr(parseOFXdatetime(s, tzinfos={"EST": ZoneInfo("US/Eastern")}))}\n\n')