You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Arrow日期转换函数返回秒数超60的问题排查

问题描述

我编写了一个Python函数date_conv,接收如2023-11-06T20:53:39.062Z的UTC时间参数,将其转换为EST(America/Toronto时区)时间后,以MM-DD-YYYY HH:MM:SS格式返回。函数代码如下:

def date_conv(time):
    est = zoneinfo.ZoneInfo('America/Toronto')
    est_time = arrow.get(time).astimezone(est)
    return str(arrow.get(est_time).format("MM-DD-YYYY HH:MM:SS"))

但该函数有时会返回如16-11-2023 15:11:79这种秒数大于60的结果,不符合预期,请问代码中存在什么问题?

问题原因与解决
  • 核心问题:重复调用arrow.get(est_time)是错误操作。est_time已经是一个Arrow对象,再次用arrow.get()包裹它时,会直接读取该对象内部可能包含的闰秒信息(比如60/61秒),而没有自动进行时间规范化,导致格式化输出了超出0-59范围的秒数。
  • 闰秒背景:UTC时间会偶尔引入闰秒来对齐地球自转,部分时间点会存在60秒的情况,但常规业务场景不需要显示这类特殊秒数。
  • 修正代码:直接使用已转换好的Arrow对象调用format()方法即可,无需二次包装:
import arrow
from zoneinfo import ZoneInfo

def date_conv(time):
    est = ZoneInfo('America/Toronto')
    est_time = arrow.get(time).astimezone(est)
    return est_time.format("MM-DD-YYYY HH:MM:SS")

同时注意补充必要的模块导入,避免运行时缺失依赖报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:09:57