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

如何将含BST、CEST等时区的字符串转换为指定格式时间戳?

处理带BST/CEST等时区的时间字符串转换问题

Python标准库的time.strptime对%Z的支持非常有限,仅能识别GMT这类通用时区缩写,无法处理BST(英国夏令时)、CEST(中欧夏令时)这类夏令时专用的时区缩写。解决这个问题的核心是明确时区缩写对应的实际时区标识符,再借助专业的时区处理库来解析。

方案1:用Python3.9+内置的zoneinfo库

无需额外安装依赖,直接使用内置的时区处理工具:

from datetime import datetime
from zoneinfo import ZoneInfo

# 按需扩展:时区缩写 -> 对应的IANA时区标识符
TZ_ABBR_MAP = {
    "BST": "Europe/London",
    "GMT": "Europe/London",
    "CEST": "Europe/Paris",
    "CET": "Europe/Paris"
}

def convert_to_target_format(time_str):
    # 拆分字符串,提取时区缩写
    time_parts = time_str.split()
    tz_abbr = time_parts[-2]
    # 重组不带时区缩写的时间字符串
    dt_str = " ".join(time_parts[:-2] + [time_parts[-1]])
    
    # 解析基础时间(无时区信息)
    naive_dt = datetime.strptime(dt_str, "%a %b %d %H:%M:%S %Y")
    # 加载对应时区并为时间对象添加时区信息
    target_tz = ZoneInfo(TZ_ABBR_MAP[tz_abbr])
    tz_aware_dt = naive_dt.replace(tzinfo=target_tz)
    
    # 转换为目标格式(示例:转成UTC时间,若要保留原时区时间直接用tz_aware_dt即可)
    return tz_aware_dt.astimezone(ZoneInfo("UTC")).strftime("%Y-%m-%d %H:%M:%S")

# 测试示例
string = 'Wed Apr 25 12:28:15 BST 2018'
string1 = 'Wed Mar 22 10:56:43 GMT 2017'
print(convert_to_target_format(string))   # 输出:2018-04-25 11:28:15
print(convert_to_target_format(string1)) # 输出:2017-03-22 10:56:43

方案2:用pytz库(兼容Python3.9以下版本)

先通过pip install pytz安装依赖,再使用如下代码:

from datetime import datetime
import pytz

TZ_ABBR_MAP = {
    "BST": "Europe/London",
    "GMT": "Europe/London",
    "CEST": "Europe/Paris",
    "CET": "Europe/Paris"
}

def convert_to_target_format(time_str):
    time_parts = time_str.split()
    tz_abbr = time_parts[-2]
    dt_str = " ".join(time_parts[:-2] + [time_parts[-1]])
    
    naive_dt = datetime.strptime(dt_str, "%a %b %d %H:%M:%S %Y")
    target_tz = pytz.timezone(TZ_ABBR_MAP[tz_abbr])
    # 用localize方法绑定时区,is_dst=None避免夏令时歧义
    tz_aware_dt = target_tz.localize(naive_dt, is_dst=None)
    
    # 转成UTC时间并格式化,若要转本地时间用tz_aware_dt.astimezone()
    return tz_aware_dt.astimezone(pytz.utc).strftime("%Y-%m-%d %H:%M:%S")

# 测试示例
string = 'Wed Apr 25 12:28:15 BST 2018'
string1 = 'Wed Mar 22 10:56:43 GMT 2017'
print(convert_to_target_format(string))   # 输出:2018-04-25 11:28:15
print(convert_to_target_format(string1)) # 输出:2017-03-22 10:56:43

注意事项

  • 时区缩写可能存在歧义(比如EST同时代表美国东部标准时间和澳大利亚东部标准时间),务必根据业务场景确认对应的IANA时区标识符,再更新TZ_ABBR_MAP
  • 如果需要处理更多时区,可参考IANA时区数据库补充映射关系

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:20:28