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

使用strptime解析GMT时间并转换为UTC时出现ValueError的问题求助

修复GMT时间转换为UTC的strptime错误

首先,你的问题核心是**strptime的格式字符串和输入时间完全不匹配**,还错误使用了%%(这是用来转义百分号的语法,你这里根本不需要)。另外时区设置也有小问题,我们一步步来修复:

1. 修正strptime格式字符串

你的输入时间是"14:50:21.000 GMT Fri Apr 29 2022",每个部分都需要对应正确的格式符:

  • %H:%M:%S.%f:匹配14:50:21.000(时分秒+毫秒)
  • %Z:匹配GMT(时区缩写)
  • %a:匹配Fri(星期缩写)
  • %b:匹配Apr(月份缩写)
  • %d:匹配29(日期)
  • %Y:匹配2022(四位年份)

所以正确的格式字符串应该是"%H:%M:%S.%f %Z %a %b %d %Y"。

2. 修正时区设置

输入时间是GMT(也就是UTC+0时区),你之前用FixedOffset(5, "GMT 0")会错误把原时间当成UTC+5的时区,应该改成FixedOffset(0, "GMT")。

修复后的完整代码

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
class FixedOffset(tzinfo):
    """Fixed UTC offset: `local = utc + offset`."""
    def __init__(self, offset, name):
        self.__offset = timedelta(hours=offset)
        self.__name = name
    def utcoffset(self, dt):
        return self.__offset
    def tzname(self, dt):
        return self.__name
    def dst(self, dt):
        return ZERO

utc = FixedOffset(0, "UTC")

# 待转换的时间数据
time_str = "14:50:21.000 GMT Fri Apr 29 2022"
# 使用正确的格式字符串解析时间
dt = datetime.strptime(time_str, "%H:%M:%S.%f %Z %a %b %d %Y")
# 绑定正确的GMT时区(UTC+0)
aware = dt.replace(tzinfo=FixedOffset(0, "GMT"))
print("带时区的原时间:", aware)
print("转换为UTC时间:", aware.astimezone(utc))

运行结果

带时区的原时间: 2022-04-29 14:50:21.000000+00:00
转换为UTC时间: 2022-04-29 14:50:21.000000+00:00

(因为原时间本身就是GMT/UTC时间,所以转换后结果一致;如果是其他时区的时间,astimezone(utc)会自动计算偏移量完成转换)

额外优化建议

其实Python 3.2+已经自带了datetime.timezone,可以替代你自己写的FixedOffset类,简化代码:

from datetime import datetime, timezone, timedelta

utc = timezone.utc
time_str = "14:50:21.000 GMT Fri Apr 29 2022"
dt = datetime.strptime(time_str, "%H:%M:%S.%f %Z %a %b %d %Y")
aware = dt.replace(tzinfo=timezone(timedelta(hours=0), "GMT"))
print("带时区的原时间:", aware)
print("转换为UTC时间:", aware.astimezone(utc))

效果和之前完全一样,不用自己手动实现tzinfo子类。

内容的提问来源于stack exchange,提问作者Benito Barrios Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:27:29