Python 读取log文本将13位时间戳转换为时间

本文介绍了一种使用Python进行日志文件中时间戳转换的方法,通过正则表达式匹配并转换时间戳为人类可读格式,展示了如何读取、处理和写入日志文件的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转换前test.log

b99fc31add4b7c041","timestamp":"1519443717289"},"event":"1ed02e727dfa0

TimeConversion.py

import time
import re

path = 'D:\\work_sql\\text.log'  # 文件路径

with open(path, 'r', encoding='utf-8') as f:
    for each_line in f:     # 遍历文件的每一行
        reg = r'"timestamp":"(.{13})'
        word_reg = re.compile(reg)
        word_reg_list = re.findall(word_reg, each_line)
        for word in word_reg_list:
            # print(word)
            word = int(word)
            timeStamp = float(word / 1000)
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            # print(otherStyleTime)
            word = str(word)
            each_lines = each_line.replace(word, otherStyleTime)
            with open('TimeConversion.log', 'a', encoding='utf-8') as f1:  # 追加写入一个文件中
                f1.write(each_lines)

转换后test.log

b99fc31add4b7c041","timestamp":"2018-02-24 11:41:57"},"event":"1ed02e727dfa0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值