python - 如何在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)
解决方案
使用re
和datetime
模块。
演示:
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
推荐阅读
- firebase - Firebase (FCM) 问题
- php - 如何从 3 维数组中获取单个变量?
- r - 向量中的第一个数据点不是我所期望的
- ruby-on-rails - 分配给关键字“new”的 Ruby 变量
- python - 在 Flask 中下载修改后的 CSV 文件
- javascript - 有没有办法使用 discord.js 计算用户的消息?
- php - 使用 AWS SDK PHP 创建 & 压缩 & 下载 S3 文件夹/多个文件
- javascript - 如何使用下面的日志信息进行计算?
- c# - 相同的文件不同的创建时间
- javascript - 如果你输入一个数字,你如何编码m 将数字与 if 子句进行比较?