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

Python:将dd/mm/yy带毫秒时间戳转成yyyy-mm-dd格式并去方括号

解决时间戳格式转换与列表去除问题

核心处理步骤

  • 提取单个时间戳字符串:re.findall返回列表结构,直接取第一个元素即可去除方括号;改用re.search能直接获取单个匹配结果,效率更高。
  • 格式转换:借助datetime模块的strptime解析原始格式,再用strftime输出符合要求的目标格式。

修改后的完整代码示例

import re
from datetime import datetime

# 时间戳匹配正则
reTimestamp = r'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}:\d{3}'

# 读取文件并处理每行数据
with open('your_input.txt', 'r') as f:
    for line in f:
        stripped_line = line.strip()
        # 用re.search获取单个匹配结果,避免返回列表
        match_result = re.search(reTimestamp, stripped_line)
        if match_result:
            # 提取原始时间戳字符串
            raw_ts = match_result.group()
            # 解析原始格式:日/月/两位年 时:分:秒:三位毫秒
            dt_obj = datetime.strptime(raw_ts, '%d/%m/%y %H:%M:%S:%f')
            # 转换为目标格式:四位年-月-日 时:分:秒.六位微秒(自动补零)
            formatted_ts = dt_obj.strftime('%Y-%m-%d %H:%M:%S.%f')
            print(formatted_ts)

关键细节说明

  • 去除列表结构:如果坚持使用re.findall,可通过timestamp[0]直接提取列表中的唯一字符串(需确保每行仅存在一个时间戳);用re.search则更直接,无需处理列表。
  • 格式匹配规则:
    • 原始格式对应指令:%d(两位日期)、%m(两位月份)、%y(两位年份)、%H(24小时制小时)、%M(分钟)、%S(秒)、%f(毫秒/微秒,原始三位会自动补零到六位)。
    • 目标格式用%Y输出四位年份,秒数后用.连接%f输出六位微秒,完全匹配datetime.now()的输出格式。

测试结果

输入原始时间戳:03/11/22 01:05:06:172
输出格式化结果:2022-11-03 01:05:06.172000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:50:44