2016-11-29 76 views
2

如何以線路協議格式顯示CSV文件,如influxdb用途?如何以行協議格式顯示csv文件?

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

Whe REAS我要出去放於lineprotocol格式/語法如:

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

而且我也想代碼能夠轉換,Time=12:05:50:274爲劃時代的時間,以便它可以在線路協議被用作時間戳influx db

回答

2

您還需要使用行的「Date」屬性,以便轉換爲紀元時間。這裏有一種方法可以做到這一點:

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

謝謝你,它正在工作......! – Allenien3256