Time series data
Displaying dates and timestamps
LightningChart Python data values are described with numbers. When it comes to Time series data, timestamps must be in Unix time format, specifically milliseconds since January 1, 1970 00:00:00 UTC.
import time
current_time = time.time() # as seconds
current_time_ms = current_time * 1000 # as milliseconds
from datetime import datetime
def timestamp_str_to_unix(timestamp_str: str, timestamp_format: str):
""" Converts a timestamp string to a Unix timestamp in milliseconds.
Args:
timestamp_str (str): The timestamp string that needs to be converted.
timestamp_format (str): The format in which the timestamp string is provided.
"""
dt = datetime.strptime(timestamp_str, timestamp_format)
unix_ms = dt.timestamp() * 1000
return int(unix_ms)
unix_timestamp = timestamp_str_to_unix("2023-09-06 12:30:45", "%Y-%m-%d %H:%M:%S")
unix_timestamp # 1693992645000
To display date & time values on the axis, change axis tick strategy to DateTime or Time:
axis.set_tick_strategy('DateTime')
Time series example with real-time data:
import lightningchart as lc
import time
import random
lc.set_license('my-license-key')
chart = lc.ChartXY()
chart.get_default_x_axis().dispose() # dispose the default x-axis
axis = chart.add_x_axis(axis_type='linear-highPrecision') # create new x-axis
axis.set_tick_strategy('DateTime') # configure the axis to show datetime formatted ticks,
axis.set_scroll_strategy(strategy='scrolling') # set the axis to scroll strategy
axis.set_interval( # configure the axis interval length, in milliseconds
start=-10_000, # 10 seconds
end=0,
stop_axis_after=False # allow the axis move as new data comes in
)
series = chart.add_line_series(
schema={
'x': {'pattern': 'progressive'},
'y': {'pattern': None},
})
chart.open(live=True)
for _ in range(1000):
x = time.time() * 1000
y = random.random()
series.append_samples(samples={
'x': [x],
'y': [y]
})
time.sleep(0.01)
chart.close()