如何以行协议格式显示csv文件?

时间:2016-11-29 18:16:53

标签: python csv influxdb

如何以行协议格式显示CSV文件,例如influxdb使用?

measurement[,tag_key1=tag_value1...]
field_key=field_value[,field_key2=field_value2] [timestamp]

假设我的csv文件如下:

Date          Time            place       status      action
2 sep 2016   12:05:50:274     abc          on         batery on
16 sep 2016  12:05:51:275     mbc          on         batery on
22 sep 2016  12:05:52:276     kabc          on        batery on

我可以使用代码逐行读取整个csv文件:

**with open('test.csv') as fp:
      for line in fp:
         print line**

我正在将o / p作为:

['Date','Time','place','status','action']
['2 sep 2016','12:05:50:274','abc','on','batery on']['16 sep 2016','12:05:51:275','mbc',     'on','batery on']['22 sep 2016','12:05:52:276','kabc','on','batery on']

我希望输出为lineprotocol格式/语法,例如:

Date=2 sep 2016,place=abc,'status=on,action=battery on,Time=12:05:50:274

此外,我希望代码能够将Time=12:05:50:274转换为纪元时间,以便它可以用作influx db的行协议中的时间戳。

1 个答案:

答案 0 :(得分:2)

您需要使用"日期"行的属性也是为了转换为纪元时间。这是你可以做到的一种方式:

from __future__ import print_function

import csv
from datetime import datetime as dt

with open('test.csv') as infile:
    headers = next(csv.reader(infile))

with open('test.csv') as infile:
    for row in csv.DictReader(infile):
        row['Time'] = dt.strptime(row['Date'] + " " + row['Time'].rsplit(":",1)[0], "%d %b %Y %H:%M:%S")
        print(','.join(["%s=%s" %(header, row[header]) for header in headers])