首页 > 解决方案 > 如何在python中的正则表达式代码中正确更改日期和时间?

问题描述

我是 python 的初学者,我有一个需要记录日期的日志文件。我使用正则表达式来获取 2 个条件,但不幸的是我的结果不符合预期,这是我得到的结果:

 Date               Time       
 20170119        193739188+0900

日志文件:

20170119 193739188+0900 elim1td001p imapserv 58124 72559 139941478487808 Note;AcctBadPswd(50/6)

我想知道如何更改正则表达式代码中的日期和时间格式以获得更好的结果?这是我的正则表达式代码:

import re
from csv import writer
log_file = '/Users/kiya/Desktop/mysql/ipscan/ip.txt'
output_file = '/Users/kiya/Desktop/mysql/ipscan/output.csv'

name_to_check = 'MBX_AUTHENTICATION_FAILED'

with open(log_file,encoding="utf-8") as infile:
    for line in infile:
        if name_to_check in line:
            username = re.search(r'(?<=userName=\[)(.*)(?=\],)', line)
            username = username.group()

            date = re.search('(?P<year>\d{4})(?P<month>\d{2})(?P<date>\d{2})', line)
            date = date.groups()

            time = re.search(r'(\d{9}\+\d{4})', line)
            time = time.group()

            ip = re.search(
                r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',
                line)
            ip = ip.group()

            with open(output_file, 'w') as outfile:
            csv_writer = writer(outfile)
            csv_writer.writerow(["Username","Date","Time","Ip_address"])
            csv_writer.writerow([username,date,time,ip])

我希望结果如下:

Date: 2017-01-09
Time: 01:15:30 (like)

标签: pythonregex

解决方案


使用redatetime模块。

演示:

import re
import datetime
s = "20170119 193739188+0900 elim1td001p imapserv 58124 72559 139941478487808 Note;AcctBadPswd(50/6)"
m = re.search("(?P<date>\d{8})\s+(?P<time>\d{9})\+(?P<zone>\d{4})", s)
if m:
    date = datetime.datetime.strptime(m.group('date'), "%Y%m%d").strftime("%Y-%m-%d")
    time = datetime.datetime.strptime(m.group('time'), "%H%M%S%f").strftime("%H:%M:%S")
    print(date)
    print(time)

输出:

2017-01-19
19:37:39

推荐阅读