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

Python Flask中如何将20210910103255格式的时间戳转换为2021/09/10 10:32:55

Python时间字符串格式化优化方案

原有代码重复执行了多次拆分取值操作,存在冗余,以下是两种更优的实现方案:

方案1:使用datetime标准库(更推荐)

该方案可读性、可维护性更高,后续如果需要调整输出格式仅需修改strftime的参数即可,同时可以自动校验时间字符串的合法性:

import datetime

# 提前提取原始时间串,避免重复拆分取值
raw_time = as_json['array_id'].split("_")[3]
# 按原格式解析为时间对象后格式化为目标样式
formatted_date = datetime.datetime.strptime(raw_time, "%Y%m%d%H%M%S").strftime("%Y/%m/%d %H:%M:%S")

"date": formatted_date

方案2:简化切片拼接(无需引入额外模块)

如果业务场景简单不需要引入datetime模块,可以用f-string简化拼接逻辑,代码更简洁易读:

raw_time = as_json['array_id'].split("_")[3]
"date": f"{raw_time[:4]}/{raw_time[4:6]}/{raw_time[6:8]} {raw_time[8:10]}:{raw_time[10:12]}:{raw_time[12:14]}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:09:03