Search code examples
python-3.xexcelinfluxdb

How to insert data into Influxdb from CSV file


I wanted to insert data from a CSV file to Influxdb. I have tried the below Python script. It was successful, but I want it to be inserted at particular time (I have a column in which date is specified).

import pandas as pd
from influxdb import InfluxDBClient

client = InfluxDBClient(host='localhost', port=8086)
client.switch_database('databse_name')

file_path = r'file_name.csv'

csvReader = pd.read_csv(file_path)

print(csvReader.shape)
print(csvReader.columns)

for row_index, row in csvReader.iterrows() : 
    tags = row[1]
    #fieldvalue = row[2]
    json_body = [
        {
            "measurement": "Measurement_name",
            "tags": {
                        "Tag_name1": tags
                    },
            "fields": {
                        "Field1": row[2],
                        "Field2": row[3], 
                        "Field3": row[4]
                        }
        }
    ]
    client.write_points(json_body)

Solution

  • Specify time in the json_body:

    json_body = [{
        "time": "<datetime, e.g. 2020-05-02T17:30:45Z>",
        "measurement": "Measurement_name",
        "tags": {
            "Tag_name1": tags
        },
        "fields": {
            "Field1": row[2],
            "Field2": row[3],
            "Field3": row[4]
        }
    }]