Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: altair chart for datetimes with no timezone expected (#3135)

Myles Scolnickd1dd79645798
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 935b035ca2..6118e8605e 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -18,6 +18,7 @@ import { Events } from "@/utils/events";
import { ErrorBanner } from "../common/error-banner";
import { Tooltip } from "@/components/ui/tooltip";
import { HelpCircleIcon } from "lucide-react";
+import { isValid } from "date-fns";
export interface Data {
spec: VegaLiteSpec;
@@ -121,11 +122,14 @@ const LoadedVegaComponent = ({
acc[name] = debounce((signalName, signalValue) => {
Logger.debug("[Vega signal]", signalName, signalValue);
+ let result = Objects.mapValues(
+ signalValue as object,
+ convertDatetimeToEpochMilliseconds,
+ );
+ result = Objects.mapValues(result, convertSetToList);
+
handleUpdateValue({
- [signalName]: Objects.mapValues(
- signalValue as object,
- convertSetToList,
- ),
+ [signalName]: result,
});
}, 100);
return acc;
@@ -245,4 +249,16 @@ function convertSetToList(value: unknown): unknown {
return value;
}
+function convertDatetimeToEpochMilliseconds(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map((v) => {
+ if (v instanceof Date && isValid(v)) {
+ return new Date(v).getTime();
+ }
+ return v;
+ });
+ }
+ return value;
+}
+
export default VegaComponent;
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 7eb6096cdf..8f6da1d8ae 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -157,7 +157,16 @@ def _resolve_values(values: Any, dtype: Any) -> List[Any]:
return datetime.date.fromtimestamp(value / 1000)
if nw.Datetime == dtype and isinstance(dtype, nw.Datetime):
if isinstance(value, str):
- return datetime.datetime.fromisoformat(value)
+ res = datetime.datetime.fromisoformat(value)
+ # If dtype has no timezone, shift by local timezone offset
+ if dtype.time_zone is None:
+ local_tz = datetime.datetime.now().astimezone().tzinfo
+ LOGGER.warning(
+ f"Datetime was given with a timezone when not expected. "
+ f"Shifting by local timezone offset {local_tz}."
+ )
+ return res.astimezone(local_tz).replace(tzinfo=None)
+ return res
# Value is milliseconds since epoch
# so we convert to seconds since epoch
diff --git a/marimo/_smoke_tests/altair/timestamp_with_no_timezone.py b/marimo/_smoke_tests/altair/timestamp_with_no_timezone.py
new file mode 100644
index 0000000000..7b0dce9db0
--- /dev/null
+++ b/marimo/_smoke_tests/altair/timestamp_with_no_timezone.py
@@ -0,0 +1,87 @@
+import marimo
+
+__generated_with = "0.9.34"
+app = marimo.App(width="full", auto_download=["html"])
+
+
+def __(alt, df, mo):
+ tmc = mo.ui.altair_chart(
+ alt.Chart(df.reset_index())
+ .mark_bar()
+ .encode(
+ x="count()",
+ y="timestamp",
+ )
+ )
+ tmc
+ return (tmc,)
+
+
+def __(tmc):
+ tmc.value
+ return
+
+
+def __(build_df, d):
+ df = build_df(d)
+ return (df,)
+
+
+def __(StringIO, date_format, pd):
+ def build_df(data: str):
+ res = pd.read_csv(StringIO(data))
+ res["timestamp"] = pd.to_datetime(
+ res["@timestamp"], format=date_format
+ ).dt.floor("s")
+ res.index = res["timestamp"]
+ res = res.rename(columns={"kubernetes.pod_name": "server"})
+
+ res = res[
+ [
+ "message",
+ "server",
+ ]
+ ]
+
+ return res
+ return (build_df,)
+
+
+def __():
+ date_format = "%b %d, %Y @ %H:%M:%S.%f"
+ return (date_format,)
+
+
+def __():
+ d = '''"@timestamp",message,severity,"kubernetes.pod_name"
+ "Nov 26, 2024 @ 00:29:59.795","time=""2024-11-26T00:29:59Z"" level=info msg=""app_disconn(device-ap-c8a608174aa0)(ap)(209766850)(1)(1)(Client Closed)(thirdparty-nats-3)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-wf775"
+ "Nov 26, 2024 @ 00:29:59.794","time=""2024-11-26T00:29:59Z"" level=info msg=""app_conn(device-ap-58fb961a30d0)(ap)(thirdparty-nats-4)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-wf775"
+ "Nov 26, 2024 @ 00:29:59.793","time=""2024-11-26T00:29:58Z"" level=info msg=""app_conn(device-ap-a80bfb3d7f80)(ap)(thirdparty-nats-4)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-wf775"
+ "Nov 26, 2024 @ 00:29:59.791","time=""2024-11-26T00:29:58Z"" level=info msg=""app_disconn(device-ap-58fb961a4220)(ap)(177150315)(0)(0)(Client Closed)(thirdparty-nats-2)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-wf775"
+ "Nov 26, 2024 @ 00:29:58.012","time=""2024-11-26T00:29:56Z"" level=info msg=""app_conn(device-ap-cc1b5a3008c0)(ap)(thirdparty-nats-1)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-rzlc5"
+ "Nov 26, 2024 @ 00:29:58.011","time=""2024-11-26T00:29:56Z"" level=info msg=""app_conn(device-ap-a80bfb3d79d0)(ap)(thirdparty-nats-3)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-rzlc5"
+ "Nov 26, 2024 @ 00:29:58.010","time=""2024-11-26T00:29:55Z"" level=info msg=""app_disconn(device-ap-d04f58243120)(ap)(87695134)(1)(1)(Client Closed)(thirdparty-nats-0)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-rzlc5"
+ "Nov 26, 2024 @ 00:29:58.009","time=""2024-11-26T00:29:55Z"" level=info msg=""app_disconn(device-ap-38453b263ef0)(ap)(37625737)(2)(1)(Client Closed)(thirdparty-nats-1)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-rzlc5"
+ "Nov 26, 2024 @ 00:29:58.008","time=""2024-11-26T00:29:53Z"" level=info msg=""app_disconn(device-ap-c8a6081727b0)(ap)(105295015)(1)(1)(Client Closed)(thirdparty-nats-3)"" @service=benthos label="""" path=root.pipeline.processors.0.workflow.processors.1 stream=sys_evts_acct_conn_disconn",,"thirdparty-benthos-fbfb4884d-rzlc5"
+ '''
+ return (d,)
+
+
+def __():
+ import marimo as mo
+ import numpy as np
+ import pandas as pd
+ from io import StringIO
+ import altair as alt
+ return StringIO, alt, mo, np, pd
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index 5d78fdf12c..d3161dd890 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -352,6 +352,28 @@ class TestAltairChart:
== 2
)
+ # Datetimes with timezone given, get remove
+ assert (
+ get_len(
+ _filter_dataframe(
+ df,
+ {
+ "select_interval": {
+ "datetime_column": [
+ datetime.datetime(
+ 2019, 12, 29, tzinfo=datetime.timezone.utc
+ ).isoformat(),
+ datetime.datetime(
+ 2020, 1, 1, tzinfo=datetime.timezone.utc
+ ).isoformat(),
+ ]
+ }
+ },
+ )
+ )
+ == 2
+ )
+
@staticmethod
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
@@ -454,6 +476,28 @@ class TestAltairChart:
== 2
)
+ # Datetimes with timezone given, get remove
+ assert (
+ get_len(
+ _filter_dataframe(
+ df,
+ {
+ "select_interval": {
+ "datetime_column": [
+ datetime.datetime(
+ 2019, 12, 29, tzinfo=datetime.timezone.utc
+ ).isoformat(),
+ datetime.datetime(
+ 2020, 1, 1, tzinfo=datetime.timezone.utc
+ ).isoformat(),
+ ]
+ }
+ },
+ )
+ )
+ == 0
+ )
+
@staticmethod
async def test_altair_settings_when_set(
k: Kernel, exec_req: ExecReqProvider