I am running the script example.py from the influxdb-client-python
code base. It runs and writes a data point to a local influxDB instance, for tests and learning purposes only.
From what I understand, this script is supposed to write a single point in 2 different ways: using line_protocol
(a string) and the Point
data structure.
I have no problem with the Point
data structure; however, the line_protocol
writes a point somewhere in February 1970. I am afraid this is a problem of WritePrecision. Maybe it should not be specified when using a Datetime
object that is converted to a line_protocol
?
Can someone please confirm this behaviour (if this is not an error on my side) and also that this is expected ? Many thanks.
So, what you're seeing with the February 1970 timestamp is likely due to the precision mismatch when you're using line protocol to write data. InfluxDB expects the timestamp in nanoseconds by default. If you don’t specify the precision, it assumes nanoseconds, and if your timestamp is off, it defaults to something like the Unix epoch start — hence, the Feb 1970 date.
You can do 2 things:
If you're using line protocol, make sure you're giving the timestamp in the right precision.
If you're using Point (like you mentioned), it handles precision for you, so you don’t have to worry about that part.
With Line Protocol:
from influxdb_client import InfluxDBClient
import datetime
client = InfluxDBClient(url="http://localhost:8086", token="your-token", org="your-org")
write_api = client.write_api()
# Timestamp in nanoseconds
timestamp = datetime.datetime.utcnow()
line_protocol = f"temperature value=23.5 {int(timestamp.timestamp() * 1e9)}"
# Write with nanosecond precision
write_api.write(bucket="your-bucket", record=line_protocol, write_precision="ns")
With Point:
from influxdb_client import InfluxDBClient, Point
import datetime
client = InfluxDBClient(url="http://localhost:8086", token="your-token", org="your-org")
write_api = client.write_api()
# Create a datetime object (UTC)
timestamp = datetime.datetime.utcnow()
# InfluxDB handles precision for you with Point
point = Point("temperature").field("value", 23.5).time(timestamp)
write_api.write(bucket="your-bucket", record=point)
TL;DR:
Hopefully this helps!