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

在Python中如何将纯数字字符串转换为指定格式的日期时间

实现方案

方法1:使用datetime模块(推荐,自带格式校验)

通过Python标准库的datetime模块先解析原始时间串,再格式化输出为目标格式,适合对输入合法性有要求的场景:

from datetime import datetime

raw_time_str = "20211111012030"
# 按照原始串的格式解析为datetime对象
dt = datetime.strptime(raw_time_str, "%Y%m%d%H%M%S")
# 转换为目标格式字符串
result = dt.strftime("%Y-%m-%d %H:%M:%S")

print(result)
# 输出:2021-11-11 01:20:30

该方案会自动校验输入内容的合法性,若输入为无效时间(比如出现13月、32日等错误值)会直接抛出异常,避免生成错误结果。

方法2:字符串切片拼接(无需导入依赖,适合固定合规输入)

如果可以保证输入一定是14位的合法时间串,可以直接按固定位置切片拼接,执行效率更高:

raw_time_str = "20211111012030"
result = f"{raw_time_str[:4]}-{raw_time_str[4:6]}-{raw_time_str[6:8]} {raw_time_str[8:10]}:{raw_time_str[10:12]}:{raw_time_str[12:]}"

print(result)
# 输出:2021-11-11 01:20:30

该方案没有校验逻辑,输入长度不对或内容非法时会直接生成错误格式的结果。


内容的提问来源于stack exchange,提问作者Ansi P.K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:36:05