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中sys.argv参数用法实例分析

本文实例讲述了python中sys.argv参数用法。分享给大家供大家参考。具体分析如下: 在学python的过程中,一直弄不明白sys.argv[]的意思,虽知道是表示命令行参数,但还...

python队列Queue的详解

Queue Queue是python标准库中的线程安全的队列(FIFO)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递 基本FIFO...

通过字符串导入 Python 模块的方法详解

通过字符串导入 Python 模块的方法详解

我们平时导入第三方模块的时候,一般使用的是 import 关键字,例如: import scrapy from scrapy.spider import Spider 但是如果各位...

Python学习笔记之自定义函数用法详解

本文实例讲述了Python学习笔记之自定义函数用法。分享给大家供大家参考,具体如下: 函数能提高应用的模块性,和代码的重复利用率。Python提供了许多内建函数,比如print()等。也...

Python读取word文本操作详解

Python读取word文本操作详解

本文研究的主要问题时Python读取word文本操作,分享了相关概念和实现代码,具体如下。 一,docx模块 Python可以利用python-docx模块处理word文档,处理方式是面...