首先需要注意的一些事情(如评论):
- Python 内置的 strptime 在这里会遇到困难 -
%z
不会解析单个数字偏移小时,%Z
也不会解析一些(可能)模棱两可的时区缩写。
然后,OFX 银行版本 2.3 文档(第 3.2.8.2 节日期和日期时间)给我留下了一些问题:
- UTC 偏移量是可选的吗?
- 为什么 EST 只是一个缩写,却被称为时区?
- 为什么在示例中 UTC 偏移量是 -5 小时,而在 1996-10-05,美国/东部时间是 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')