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
相关产品推荐
相关产品推荐

