5

I am using the following lines of code to add metrics data in influxDB.

    def add_job_influx_db_metrics(tags_dict={}, values_dict={}, measurement='test'):
       influxdb_client = InfluxDB.get_connection()
       db_name = "mydb"
       influxdb_client.switch_database(database=db_name)
       current_time = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.localtime(time.time()))
       json_body = [
        {
          "measurement": measurement,
          "tags": tags_dict,
          "time": current_time,
          "fields": values_dict
         }
       ]
      response = influxdb_client.write_points(points=json_body)
      print "write_operation response", response

When I am integrating it with Grafana,data does not come up but when I am checking it on 127.0.0.1:8083 ,it shows the time is 1970-01-01T00:00:00Z.Probably,it takes the start epoch time as default. I wanted to take the time of the form "2015-8-19T07:15:00Z". How to take the time field in influxdb(python client) and what is timePrecision ?

2 Answers 2

23
 from datetime import datetime
 current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

and use "time" like this in json_body-

"time": current_time

It works.

6

You need UNIX timestamp, so it should be:

"time": int(time.time())

Edit:

Time with nanosecond time precision:

"time": int(time.time() * 1000000000)

Eventually, second precision can be used "time": int(time.time()) and specified explicitly:

 write_points(points, time_precision='s')
4
  • 1
    Using an integer, as Jan Garaj suggests, avoids the string conversion needed when doing someting like datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    – rbinnun
    Dec 27, 2016 at 22:53
  • this would not work as the time value is different int(time.time()) gives 1582753973 where the db will need 1582753928000000000 Feb 26, 2020 at 21:56
  • @PeterMoore you are right. So int(time.time()) can be multiplied to get nanosecond time precision or write_points(points, time_precision='s') can be used to specify second time precision.
    – Jan Garaj
    Feb 26, 2020 at 23:19
  • correct. you probably should edit your post so people don't get confused. oh and since i took this approach int(time.time() * 1000000000) it does preserve microsecond precision on time Feb 26, 2020 at 23:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.