Python如何将带UTC偏移和时区缩写的时间字符串转为UNIX时间戳
问题原因
- Python 标准库
strptime的%Z格式符对时区缩写的支持高度依赖操作系统,大部分平台无法正确识别 PDT、CST 这类地区性时区缩写,会直接抛出格式不匹配错误。 - 你提供的时间字符串已经包含了精确的 UTC 偏移量
-0700,括号里的时区缩写属于冗余信息,无需强行适配%Z规则。
解决方法
先预处理时间字符串,剔除末尾括号包裹的时区缩写部分,再用原有规则解析即可。同时推荐直接用带时区的 datetime 对象自带的 timestamp() 方法生成 Unix 时间戳,避免 time.mktime 因本地时区差异导致的计算错误:
import datetime datestring1 = "Mon, 14 May 2001 16:39:00 -0700" datestring2 = "Mon, 14 May 2001 16:39:00 -0700 (PDT)" # 通用预处理:移除末尾括号内的时区缩写 def clean_datestring(s): if ' (' in s and s.endswith(')'): return s.rsplit('(', 1)[0].strip() return s # 解析转换为时间戳 ts1 = datetime.datetime.strptime(clean_datestring(datestring1), "%a, %d %b %Y %H:%M:%S %z").timestamp() ts2 = datetime.datetime.strptime(clean_datestring(datestring2), "%a, %d %b %Y %H:%M:%S %z").timestamp() print(ts1) # 输出 989883540.0 print(ts2) # 输出与ts1完全一致,符合预期
内容的提问来源于stack exchange,提问作者Marcus Willems
相关产品推荐
相关产品推荐

