python每5分钟从kafka中提取数据的例子

yipeiwu_com5年前Python基础

我就废话不多说了,直接上代码吧!

import sys
sys.path.append("..")
from datetime import datetime
from utils.kafka2file import KafkaDownloader
import os
"""
实现取kafka数据,文件按照取数据的间隔命名
如每5分钟从kafka取数据写入文件中,文件名为当前时间加5
"""

TOPIC = "rtz_queue"
HOSTS = "ip:9092,ip:9092"
GROUP = "2001"

def get_end_time(hour,minute,time_step):
 if (minute+time_step)%60<60:
  if (minute+time_step)%60<10:
   return str(hour+int((minute+time_step)/60))+":"+"0"+str((minute+time_step)%60)
  else:
   return str(hour+int((minute+time_step)/60))+":"+str((minute+time_step)%60)
 else:
  pass

def kafkawritefile(time_step,time_num):
 start = datetime.now()
 downloader = KafkaDownloader(HOSTS, TOPIC, GROUP)
 i = 1
 while(i<=time_num):
  end_time = get_end_time(start.hour, start.minute,i*time_step)
  end_time_file = end_time.replace(':', '_')
  outfile_path = "/data/tmp/" + end_time_file + ".csv"

  if os.path.exists(outfile_path):
   os.remove(outfile_path)
  writefile = open(outfile_path, 'a+', encoding='utf-8')
  
  for msg in downloader.message():
   curr_time = datetime.now()
   curr_time = str(curr_time)
   split_curr_time = curr_time.split(' ')
   curr_time_str = split_curr_time[1][0:5]
  
   if curr_time_str >= str(end_time):  
    break
  i += 1

if __name__=='__main__':
 time_step = 15
 time_num = 1
 kafkawritefile(time_step,time_num)

以上这篇python每5分钟从kafka中提取数据的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现批量改文件名称的方法

本文实例讲述了python实现批量改文件名称的方法。分享给大家供大家参考。具体分析如下: 发现python中提供了大量的模块函数,有时候一些系统操作在python中非常简单 下面的文件关...

python实现八大排序算法(2)

python实现八大排序算法(2)

本文接上一篇博客python实现的八大排序算法part1,将继续使用python实现八大排序算法中的剩余四个:快速排序、堆排序、归并排序、基数排序 5、快速排序 快速排序是通常被认为在同...

OpenCV实现人脸识别

主要有以下步骤: 1、人脸检测 2、人脸预处理 3、从收集的人脸训练机器学习算法 4、人脸识别 5、收尾工作 人脸检测算法: 基于Haar的脸部检测器的基本思想是,对于面部正面大部分区域...

Python 使用 prettytable 库打印表格美化输出功能

Python 使用 prettytable 库打印表格美化输出功能

pip install prettytable 每次添加一行 from prettytable import PrettyTable # 默认表头:Field 1、Field 2....

使用python实现画AR模型时序图

使用python实现画AR模型时序图

背景: 用python画AR模型的时序图。 结果: 代码: import numpy as np import matplotlib.pyplot as plt """ AR(1)...