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

如何在Python中不使用replace,用strptime转换含字符的字符串为datetime

不用replace将带中间字符的日期字符串转为datetime对象

核心解决方案:利用strptime格式字符串匹配固定/可变中间字符

你的问题核心是字符串中间固定位置的字符干扰了日期解析,完全不需要用replace,直接在strptime的格式字符串里把这个字符写进去,或者用通配符跳过即可——这种方式基于底层C实现,效率远高于Python层面的字符串替换。

情况1:中间字符固定(如示例中的'A')

直接把固定字符嵌入格式字符串:

from datetime import datetime
x = '20220117A1745'
dt = datetime.strptime(x, "%Y%m%dA%H%M")
print(dt)  # 输出:2022-01-17 17:45:00

情况2:中间字符是任意单个字符

如果中间的字符不固定(比如有时是'A',有时是'B'),可以用%*c跳过一个任意字符:

x = '20220117B1745'
dt = datetime.strptime(x, "%Y%m%d%*c%H%M")
print(dt)  # 输出:2022-01-17 17:45:00

效率优势说明

datetime.strptime的格式解析逻辑是在C语言层面实现的,不需要在Python代码中对字符串进行replace这类内存拷贝操作。对于数十万条数据的循环处理,这种方式的性能会比replace+strptime的组合高出很多,避免了Python字符串操作带来的额外开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:21:35