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.

feat: add precision option to mo.ui.datetime (#7251)

Myles Scolnick6ff03721e868
diff --git a/frontend/src/plugins/impl/DateTimePickerPlugin.tsx b/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
index 78406f86ba..74e7578ed4 100644
--- a/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
+++ b/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
@@ -14,6 +14,7 @@ interface Data {
start: string;
stop: string;
step?: string;
+ precision: "hour" | "minute" | "second";
fullWidth: boolean;
disabled?: boolean;
}
@@ -27,6 +28,7 @@ export class DateTimePickerPlugin implements IPlugin<T, Data> {
start: z.string(),
stop: z.string(),
step: z.string().optional(),
+ precision: z.enum(["hour", "minute", "second"]).default("minute"),
fullWidth: z.boolean().default(false),
disabled: z.boolean().optional(),
});
@@ -63,7 +65,7 @@ const DateTimePickerComponent = (props: DateTimePickerProps): JSX.Element => {
return (
<Labeled label={props.label} fullWidth={props.fullWidth}>
<DatePicker
- granularity="minute"
+ granularity={props.precision}
value={parsedValue}
onChange={handleInput}
aria-label={props.label ?? "date time picker"}
diff --git a/frontend/src/plugins/impl/__tests__/DateTimePickerPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/DateTimePickerPlugin.test.tsx
index 1f951e3ee2..9334c5889f 100644
--- a/frontend/src/plugins/impl/__tests__/DateTimePickerPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/DateTimePickerPlugin.test.tsx
@@ -11,6 +11,7 @@ interface DateTimeData {
label: string | null;
start: string;
stop: string;
+ precision: "hour" | "minute" | "second";
fullWidth: boolean;
}
@@ -37,6 +38,7 @@ describe("DateTimePickerPlugin", () => {
label: null,
start: "2024-01-01T00:00:00",
stop: "2024-12-31T23:59:59",
+ precision: "minute",
fullWidth: false,
},
functions: {},
@@ -68,6 +70,7 @@ describe("DateTimePickerPlugin", () => {
// These are the exact values that datetime.min and datetime.max produce
start: "0001-01-01T00:00:00",
stop: "9999-12-31T23:59:59",
+ precision: "minute",
fullWidth: false,
},
functions: {},
diff --git a/marimo/_plugins/ui/_impl/dates.py b/marimo/_plugins/ui/_impl/dates.py
index 52436dfeee..b038d8a5cd 100644
--- a/marimo/_plugins/ui/_impl/dates.py
+++ b/marimo/_plugins/ui/_impl/dates.py
@@ -6,6 +6,7 @@ from typing import (
Any,
Callable,
Final,
+ Literal,
Optional,
Union,
cast,
@@ -206,6 +207,7 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
start (datetime.datetime | str, optional): The minimum selectable datetime. Defaults to minimum datetime.
stop (datetime.datetime | str, optional): The maximum selectable datetime. Defaults to maximum datetime.
value (datetime.datetime | str, optional): Default value.
+ precision (Literal["hour", "minute", "second"], optional): The precision of the datetime picker. Defaults to "minute".
label (str, optional): Markdown label for the element.
on_change (Callable[[Optional[datetime.datetime]], None], optional): Optional callback to run when this element's value changes.
full_width (bool, optional): Whether the input should take up the full width of its container.
@@ -221,6 +223,7 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
stop: Optional[dt.datetime | str] = None,
value: Optional[dt.datetime | str] = None,
*,
+ precision: Literal["hour", "minute", "second"] = "minute",
label: Optional[str] = None,
on_change: Optional[Callable[[Optional[dt.datetime]], None]] = None,
full_width: bool = False,
@@ -233,8 +236,14 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
if isinstance(value, str):
value = self._convert_value(value)
+ if precision not in ("hour", "minute", "second"):
+ raise ValueError(
+ f"precision must be 'hour', 'minute', or 'second', got {precision}"
+ )
+
self._start = dt.datetime.min if start is None else start
self._stop = dt.datetime.max if stop is None else stop
+ self._precision = precision
if self._stop < self._start:
raise ValueError(
@@ -265,6 +274,7 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
args={
"start": self._start.isoformat(timespec="seconds"),
"stop": self._stop.isoformat(timespec="seconds"),
+ "precision": precision,
"full-width": full_width,
"disabled": disabled,
},
diff --git a/tests/_plugins/ui/_impl/test_dates.py b/tests/_plugins/ui/_impl/test_dates.py
index 4bb8881512..a68397d88d 100644
--- a/tests/_plugins/ui/_impl/test_dates.py
+++ b/tests/_plugins/ui/_impl/test_dates.py
@@ -192,3 +192,29 @@ def test_date_range_from_dataframe() -> None:
)
assert date_range_ui.start == datetime.date(2024, 1, 1)
assert date_range_ui.stop == datetime.date(2024, 1, 31)
+
+
+def test_datetime_precision_default() -> None:
+ """Test that datetime precision defaults to 'minute'."""
+ dt = ui.datetime(value="2024-01-01T12:30:45")
+
+ # Check that precision is set to "minute" by default in the args
+ precision = dt._args.args.get("precision")
+ assert precision == "minute"
+
+
+def test_datetime_precision_validation() -> None:
+ """Test that datetime precision validation raises ValueError for invalid values."""
+ # Valid precisions should work
+ dt_hour = ui.datetime(value="2024-01-01T12:30:45", precision="hour")
+ assert dt_hour._args.args.get("precision") == "hour"
+
+ dt_minute = ui.datetime(value="2024-01-01T12:30:45", precision="minute")
+ assert dt_minute._args.args.get("precision") == "minute"
+
+ dt_second = ui.datetime(value="2024-01-01T12:30:45", precision="second")
+ assert dt_second._args.args.get("precision") == "second"
+
+ # Invalid precision should raise ValueError
+ with pytest.raises(ValueError, match="precision must be"):
+ ui.datetime(value="2024-01-01T12:30:45", precision="millisecond") # type: ignore[arg-type]