python - 一种从行中提取 datetime.now 格式的方法?
问题描述
我有一个日志文件,其中包含诸如
### 192.168.70.10 on 2018-06-19 23:57:37.846200 ###
### 192.168.70.11 on 2018-06-19 23:50:33.073267 ###
它还可能包含不同行的其他数据。
我想打印以### 开头的所有行并提取它们的日期/时间,以便我可以将它们与另一个日期/时间进行比较。
我怎样才能做到这一点?我应该使用正则表达式吗?
这是我正在做的一个例子......
try:
with open('myfile.log', 'r') as myfile:
for line in myfile:
if "###" in line:
x = line
print(x)
# get date and time from x
myfile.close
except OSError as e:
print (e)
解决方案
您可以在此类问题中使用正则表达式
try:
with open('myfile.log', 'r') as myfile:
reg = re.compile('^###.*on\s([\w\s.:-]*)')
for line in myfile:
m = reg.match(line)
if m:
datetime.striptime(m.group(1), "%Y-%m-%d %H:%M:%S.%f")
推荐阅读
- android - 在垂直和水平方向的 ScrollView 内生成文本
- c# - 无法修改拆箱转换 ASP.Net 的结果
- javascript - 如何在 Javascript 数组中查找单词(字符串)?
- kubernetes - kubernetes:部署kong helm chart
- sql - 为什么插入到具有主键/标识列的表中会生成“列名或提供的值的数量与表定义不匹配”错误
- xml - 具有多个命名空间的 XML 解析
- php - WordPress帖子数:Y中的X?
- gradle - Gradle 自定义任务实现:找不到参数的方法
- android - 软件键盘打开时调整图像大小
- javascript - Chrome 中的高精度 FPS 测量