You need to enable JavaScript to run this app. Python Arrow库转换无日期纯时间字符串时区偏移异常及解决方案
优惠活动
大模型
产品
解决方案
定价
更多

Python Arrow库转换无日期纯时间字符串时区偏移异常及解决方案

Arrow 无日期纯时间字符串时区转换偏移异常处理

异常现象

使用Arrow库解析仅含时分和UTC偏移的无日期时间字符串,执行跨时区转换时会出现完全不符合预期的偏移结果,具体复现代码:

start      = '18:30+0000'
start_time = arrow.get(start,'hh:mmZ')

print(start_time.format('hh:mm A ZZ'))

print(start_time.to('Australia/Melbourne').format('hh:mm A ZZ'))
# 预期输出05:30 AM +11:00,实际显示为04:09 AM +09:39

将目标时区更换为Europe/London后,偏移异常依然存在:

print(start_time.to('Europe/London').format('hh:mm A ZZ'))
# 预期输出06:30 PM +00:00,实际显示为06:28 PM -00:01

对照验证

对照测试显示,使用Arrow原生方法获取当前UTC时间再做跨时区转换的流程完全正常,无同类偏移异常:

print(arrow.utcnow().to('Australia/Melbourne').format('hh:mm A ZZ'))

修复方案

Arrow解析无日期纯时间字符串时,会自动填充不符合IANA时区规则的占位日期,导致时区计算引用了历史上的非标准偏移值。
修复时只需在解析阶段主动补充固定的临时参照日期,即可让时区计算逻辑获取到合规的偏移规则,实现代码如下:

def convert_timezone(time_to_convert, timezone):
    # 拼接固定临时日期作为时区计算的基准
    time_to_convert = '20111111 ' + time_to_convert
    return arrow.get(time_to_convert).to(timezone)

# 转换测试
print(convert_timezone('18:30+0000','Australia/Melbourne').format('hh:mm A ZZ'))

内容的提问来源于stack exchange,提问作者Saqib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 13:45:08