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

如何用Python将长格式日期时间字符串转换为指定格式?

用datetime库转换ISO日期时间字符串格式

当然有更可靠简洁的方法,用Python标准库datetime就能搞定,比字符串切片靠谱多了——切片全靠固定位置硬切,哪天日期格式变了(比如毫秒位数变了、时区标识改了)直接就崩了,用datetime是按规则解析,兼容性强。

给你两种常用写法:

方法一:用strptime解析+strftime格式化

适用于所有Python版本,直接指定匹配格式:

from datetime import datetime

date_str = "2017-08-05T05:21:10.6582942Z"
# 按原字符串格式解析,%z处理UTC时区的Z标识
dt_obj = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
# 格式化为你要的样式
new_date = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print(new_date)  # 输出:2017-08-05 05:21:10

方法二:Python3.7+用fromisoformat简化

Python3.7及以上支持fromisoformat,只需要把末尾的Z替换成UTC时区标识+00:00就能直接解析:

from datetime import datetime

date_str = "2017-08-05T05:21:10.6582942Z"
dt_obj = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
new_date = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print(new_date)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:05:28