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

Python datetime.strptime解析PST时区报错,UTC正常如何解决?

解决datetime.strptime解析PST时区报错的问题

嘿,这个问题我之前踩过坑!原因其实很明确:Python标准库的datetime.strptime里的%Z指令对时区缩写的支持非常有限——它只认系统本地时区的缩写和少数通用时区(比如UTC、GMT),像PST这种地区性时区缩写默认不在它的识别清单里,所以会抛出ValueError。

下面给你两个实用的解决方案:

方案一:手动替换时区缩写为UTC偏移量

PST对应的是UTC-8,我们可以先把字符串里的PST替换成-0800(%z指令支持±HHMM格式的偏移量),再用strptime解析:

from datetime import datetime

string12 = '18:52:31.868 PST Fri Jan 17 2020\r'
# 替换PST为对应的UTC偏移量
modified_string = string12.replace('PST', '-0800')
# 注意这里把%Z换成%z
dt = datetime.strptime(modified_string, "%H:%M:%S.%f %z %a %b %d %Y\r")
print(dt)
# 输出:datetime.datetime(2020, 1, 17, 18, 52, 31, 868000, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600)))

这个方法不需要额外安装库,但缺点是你得提前知道每个时区缩写对应的UTC偏移量,而且要处理夏令时的话(比如PDT是UTC-7)会比较麻烦。

方案二:用第三方库python-dateutil(更灵活可靠)

dateutil库对时区的支持比标准库友好太多,能自动识别绝大多数时区缩写,还能处理夏令时的切换。

首先安装库:

pip install python-dateutil

然后有两种使用方式:

方式1:用parser自动解析

不需要手动指定格式,直接让库自动识别时间字符串:

from dateutil import parser

string12 = '18:52:31.868 PST Fri Jan 17 2020\r'
dt = parser.parse(string12)
print(dt)
# 输出:datetime.datetime(2020, 1, 17, 18, 52, 31, 868000, tzinfo=tzoffset(None, -28800))

方式2:配合strptime和指定时区

如果你想保留原格式字符串,可以用dateutil.tz.gettz()来指定时区:

from datetime import datetime
from dateutil.tz import gettz

string12 = '18:52:31.868 PST Fri Jan 17 2020\r'
# 先解析(此时时区信息为None),再手动添加tzinfo
dt = datetime.strptime(string12, "%H:%M:%S.%f %Z %a %b %d %Y\r").replace(tzinfo=gettz('PST'))
print(dt)

这个方案更适合处理多种时区的场景,不用自己维护偏移量映射表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:12:51