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

Python中如何将2021-09-01T14:37:40.537Z转为目标时间格式

Python转换Hive存储的ISO格式UTC时间字符串实现方法

针对Hive输出的格式为2021-09-01T14:37:40.537Z的UTC时间字符串,转换为2021-09-01T14:37:40.5370000+00:00格式,可按以下两种方案实现:

方案1:标准库实现(无第三方依赖,推荐单条数据处理场景)

不需要安装额外依赖,兼容所有Python3版本,适合接口、脚本等轻量场景:

from datetime import datetime, timezone

def convert_utc_time(origin_str: str) -> str:
    # 替换Z为UTC时区标识,兼容3.11以下Python版本
    parsed_dt = datetime.fromisoformat(origin_str.replace("Z", "+00:00"))
    # 统一转换为UTC时区
    utc_dt = parsed_dt.astimezone(timezone.utc)
    # 拼接基础时间格式
    base_part = utc_dt.strftime("%Y-%m-%dT%H:%M:%S")
    # 微秒为6位数字,末尾补0凑够要求的7位小数
    microsecond_part = f"{utc_dt.microsecond:06d}0"
    return f"{base_part}.{microsecond_part}+00:00"

# 测试样例
origin_time = "2021-09-01T14:37:40.537Z"
print(convert_utc_time(origin_time))
# 输出结果:2021-09-01T14:37:40.5370000+00:00

方案2:Pandas向量化实现(适合批量处理Hive表读取的数据集场景)

如果是从Hive批量读取数据后做整列转换,用Pandas向量化逻辑性能更高,不需要写循环:

import pandas as pd

def batch_convert_time(time_series: pd.Series) -> pd.Series:
    # 批量解析为UTC时间类型
    dt_series = pd.to_datetime(time_series, utc=True)
    # %f输出6位微秒,末尾补0凑够7位小数,拼接时区偏移
    return dt_series.dt.strftime("%Y-%m-%dT%H:%M:%S.%f0+00:00")

# 测试样例
time_col = pd.Series(["2021-09-01T14:37:40.537Z", "2021-10-02T08:12:05.12Z"])
print(batch_convert_time(time_col))
# 输出结果:
# 0    2021-09-01T14:37:40.5370000+00:00
# 1    2021-10-02T08:12:05.1200000+00:00
# dtype: object

注意事项

  • 原字符串末尾的Z是UTC时区的标准标识,对应偏移量固定为+00:00,转换时不需要做额外的时区偏移计算
  • 转换逻辑会自动补全小数秒位数:如果原字符串小数秒不足3位,会先补零到毫秒精度,再补零凑够要求的7位小数
  • Python 3.11+版本的datetime.fromisoformat原生支持解析末尾带Z的ISO时间字符串,代码中保留replace("Z", "+00:00")逻辑是为了兼容3.11以下的Python版本,可根据运行环境选择是否保留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:12:31