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

2024-09-25 08:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

假设我的csv文件如下:

^{pr2}$

我可以使用以下代码逐行读取整个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']

而我希望输出到in-lineprotocol格式/语法,例如:

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

我还希望代码能够将Time=12:05:50:274转换成epoch时间,这样它就可以作为influx db的行协议中的时间戳。在


Tags: 文件csv代码in协议fielddatetime
1条回答
网友
1楼 · 发布于 2024-09-25 08:28:41

您还需要使用行的“Date”属性,以便转换为epoch时间。有一种方法可以做到:

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])

相关问题 更多 >