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: render polars dates in UTC when a timezone is specified (#4078)

Myles Scolnick1720b30bd274
diff --git a/frontend/package.json b/frontend/package.json
index 637a4452b0..19576f4c25 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -27,6 +27,7 @@
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.36.4",
"@dagrejs/dagre": "^1.1.4",
+ "@date-fns/tz": "^1.2.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 44e3c16ca3..f52668948e 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -57,6 +57,9 @@ importers:
'@dagrejs/dagre':
specifier: ^1.1.4
version: 1.1.4
+ '@date-fns/tz':
+ specifier: ^1.2.0
+ version: 1.2.0
'@dnd-kit/core':
specifier: ^6.3.1
@@ -1069,6 +1072,9 @@ packages:
resolution: {integrity: sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==}
engines: {node: '>17.0.0'}
+ '@date-fns/[email protected]':
+ resolution: {integrity: sha512-LBrd7MiJZ9McsOgxqWX7AaxrDjcFVjWH/tIKJd7pnR7McaslGYOP1QmmiBXdJH/H/yLCT+rcQ7FaPBUxRGUtrg==}
+
'@dnd-kit/[email protected]':
resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
peerDependencies:
@@ -9692,6 +9698,8 @@ snapshots:
'@dagrejs/[email protected]': {}
+ '@date-fns/[email protected]': {}
+
dependencies:
react: 18.3.1
diff --git a/frontend/src/components/data-table/__tests__/types.test.ts b/frontend/src/components/data-table/__tests__/types.test.ts
new file mode 100644
index 0000000000..3c66fe3ae9
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/types.test.ts
@@ -0,0 +1,30 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { extractTimezone } from "../types";
+
+describe("extractTimezone", () => {
+ it("should return undefined when dtype is undefined", () => {
+ expect(extractTimezone(undefined)).toBe(undefined);
+ });
+
+ it("should return undefined when dtype is not a datetime with timezone", () => {
+ expect(extractTimezone("string")).toBe(undefined);
+ expect(extractTimezone("int64")).toBe(undefined);
+ expect(extractTimezone("float64")).toBe(undefined);
+ expect(extractTimezone("date")).toBe(undefined);
+ expect(extractTimezone("datetime")).toBe(undefined);
+ expect(extractTimezone("datetime[]")).toBe(undefined);
+ });
+
+ it("should return the timezone for datetime with timezone format", () => {
+ expect(extractTimezone("datetime[ns,UTC]")).toBe("UTC");
+ expect(extractTimezone("datetime[ns,US/Eastern]")).toBe("US/Eastern");
+ expect(extractTimezone("datetime[ms,Europe/London]")).toBe("Europe/London");
+ expect(extractTimezone("datetime[s,UTC]")).toBe("UTC");
+ expect(extractTimezone("datetime[s,US/Eastern]")).toBe("US/Eastern");
+ expect(extractTimezone("datetime[s,Europe/London]")).toBe("Europe/London");
+ expect(extractTimezone("datetime[m,UTC]")).toBe("UTC");
+ expect(extractTimezone("datetime[m,US/Eastern]")).toBe("US/Eastern");
+ expect(extractTimezone("datetime[m,Europe/London]")).toBe("Europe/London");
+ });
+});
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 4fa96058ec..dfe7fe4315 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -15,6 +15,7 @@ import {
type DataTableSelection,
INDEX_COLUMN_NAME,
type FieldTypesWithExternalType,
+ extractTimezone,
} from "./types";
import { UrlDetector } from "./url-detector";
import { cn } from "@/utils/cn";
@@ -238,6 +239,7 @@ export function generateColumns<T>({
// e.g. 2010-10-07 17:15:00
const type =
column.columnDef.meta?.dataType === "date" ? "date" : "datetime";
+ const timezone = extractTimezone(column.columnDef.meta?.dtype);
return (
<div
onClick={selectCell}
@@ -249,7 +251,7 @@ export function generateColumns<T>({
)}
>
<DatePopover date={value} type={type}>
- {exactDateTime(value)}
+ {exactDateTime(value, timezone)}
</DatePopover>
</div>
);
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
index 4630a24160..f35b340303 100644
--- a/frontend/src/components/data-table/types.ts
+++ b/frontend/src/components/data-table/types.ts
@@ -38,3 +38,14 @@ export type DataTableSelection =
| "single-cell"
| "multi-cell"
| null;
+
+export function extractTimezone(dtype: string | undefined): string | undefined {
+ if (!dtype) {
+ return undefined;
+ }
+ // Check for datetime[X,Y] format
+ // We do this for any timezone-aware datetime type
+ // not just UTC (as this is what Polars does by default)
+ const match = /^datetime\[[^,]+,([^,]+)]$/.exec(dtype);
+ return match?.[1]?.trim();
+}
diff --git a/frontend/src/utils/__tests__/dates.test.ts b/frontend/src/utils/__tests__/dates.test.ts
new file mode 100644
index 0000000000..3c9190a194
--- /dev/null
+++ b/frontend/src/utils/__tests__/dates.test.ts
@@ -0,0 +1,120 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it, beforeAll, afterAll } from "vitest";
+import { prettyDate, exactDateTime, timeAgo, getShortTimeZone } from "../dates";
+
+describe("dates", () => {
+ // Save original timezone
+ let originalTimezone: string | undefined;
+
+ // Set up a fixed timezone for tests
+ beforeAll(() => {
+ originalTimezone = process.env.TZ;
+ process.env.TZ = "UTC";
+ });
+
+ // Restore original timezone
+ afterAll(() => {
+ process.env.TZ = originalTimezone;
+ });
+
+ describe("prettyDate", () => {
+ it("returns empty string for null or undefined", () => {
+ expect(prettyDate(null, "date")).toBe("");
+ expect(prettyDate(undefined, "date")).toBe("");
+ });
+
+ it("formats date correctly", () => {
+ const date = new Date("2023-05-15T12:00:00Z");
+ // Using a regex to match the pattern since exact format may vary by locale
+ expect(prettyDate(date.toISOString(), "date")).toMatch(/May 15, 2023/);
+ });
+
+ it("formats datetime correctly", () => {
+ const date = new Date("2023-05-15T12:00:00Z");
+ expect(prettyDate(date.toISOString(), "datetime")).toMatch(
+ /May 15, 2023/,
+ );
+ });
+
+ it("handles errors gracefully", () => {
+ expect(prettyDate("invalid-date", "date")).toBe("Invalid Date");
+ });
+ });
+
+ describe("exactDateTime", () => {
+ it("formats date without milliseconds", () => {
+ const date = new Date("2023-05-15T12:00:00.000Z");
+ expect(exactDateTime(date, undefined)).toBe("2023-05-15 12:00:00");
+ });
+
+ it("formats date with milliseconds", () => {
+ const date = new Date("2023-05-15T12:00:00.123Z");
+ expect(exactDateTime(date, undefined)).toBe("2023-05-15 12:00:00.123");
+ });
+
+ it("formats date in UTC when renderInUTC is true", () => {
+ const date = new Date("2023-05-15T12:00:00.000Z");
+ expect(exactDateTime(date, "UTC")).toBe("2023-05-15 12:00:00 UTC");
+ });
+
+ it("formats date with milliseconds in UTC when renderInUTC is true", () => {
+ const date = new Date("2023-05-15T12:00:00.123Z");
+ expect(exactDateTime(date, "UTC")).toBe("2023-05-15 12:00:00.123 UTC");
+ });
+
+ it("formats date in America/New_York timezone", () => {
+ const date = new Date("2023-05-15T12:00:00.000Z");
+ expect(exactDateTime(date, "America/New_York")).toBe(
+ "2023-05-15 08:00:00 EDT",
+ );
+ });
+
+ it("formats date with milliseconds in America/New_York timezone", () => {
+ const date = new Date("2023-05-15T12:00:00.123Z");
+ expect(exactDateTime(date, "America/New_York")).toBe(
+ "2023-05-15 08:00:00.123 EDT",
+ );
+ });
+ });
+
+ describe("timeAgo", () => {
+ it("returns empty string for null, undefined, or 0", () => {
+ expect(timeAgo(null)).toBe("");
+ expect(timeAgo(undefined)).toBe("");
+ expect(timeAgo(0)).toBe("");
+ });
+
+ it("formats today's date correctly", () => {
+ const today = new Date();
+ const result = timeAgo(today.toISOString());
+ expect(result).toMatch(/Today at/);
+ });
+
+ it("formats yesterday's date correctly", () => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ const result = timeAgo(yesterday.toISOString());
+ expect(result).toMatch(/Yesterday at/);
+ });
+
+ it("formats older dates correctly", () => {
+ const oldDate = new Date("2020-01-01T12:00:00Z");
+ const result = timeAgo(oldDate.toISOString());
+ expect(result).toMatch(/Jan 1, 2020 at/);
+ });
+
+ it("handles errors gracefully", () => {
+ expect(timeAgo("invalid-date")).toBe("Invalid Date at Invalid Date");
+ });
+ });
+
+ describe("getShortTimeZone", () => {
+ it("returns the short timezone", () => {
+ expect(getShortTimeZone("America/New_York")).toBeOneOf(["EDT", "EST"]);
+ });
+
+ it("handles errors gracefully", () => {
+ expect(getShortTimeZone("MarimoLand")).toBe("MarimoLand");
+ });
+ });
+});
diff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.ts
index a085c67b1c..088136cce0 100644
--- a/frontend/src/utils/dates.ts
+++ b/frontend/src/utils/dates.ts
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { formatDate } from "date-fns";
+import { TZDate } from "@date-fns/tz";
import { Logger } from "./Logger";
export function prettyDate(
@@ -34,12 +35,45 @@ export function prettyDate(
* If the date has sub-second precision, it should say "2024-10-07 17:15:00.123".
* Otherwise, it should say "2024-10-07 17:15:00".
*/
-export function exactDateTime(value: Date): string {
+export function exactDateTime(
+ value: Date,
+ timezone: string | undefined,
+): string {
const hasSubSeconds = value.getUTCMilliseconds() !== 0;
- if (hasSubSeconds) {
- return formatDate(value, "yyyy-MM-dd HH:mm:ss.SSS");
+ try {
+ if (timezone) {
+ const valueWithTimezone = new TZDate(value, timezone);
+ const shortTimeZone = getShortTimeZone(timezone);
+ if (hasSubSeconds) {
+ return `${formatDate(valueWithTimezone, "yyyy-MM-dd HH:mm:ss.SSS")} ${shortTimeZone}`;
+ }
+ return `${formatDate(valueWithTimezone, "yyyy-MM-dd HH:mm:ss")} ${shortTimeZone}`;
+ }
+
+ if (hasSubSeconds) {
+ return formatDate(value, "yyyy-MM-dd HH:mm:ss.SSS");
+ }
+
+ return formatDate(value, "yyyy-MM-dd HH:mm:ss");
+ } catch (error) {
+ Logger.warn("Failed to parse date", error);
+ return value.toISOString();
+ }
+}
+
+export function getShortTimeZone(timezone: string): string {
+ try {
+ const abbrev = new Intl.DateTimeFormat("en-US", {
+ timeZone: timezone,
+ timeZoneName: "short",
+ })
+ .formatToParts(new Date())
+ .find((part) => part.type === "timeZoneName")?.value;
+ return abbrev ?? "";
+ } catch (error) {
+ Logger.warn("Failed to get abbrev", error);
+ return timezone;
}
- return formatDate(value, "yyyy-MM-dd HH:mm:ss");
}
/**
diff --git a/marimo/_smoke_tests/polars/timezones.py b/marimo/_smoke_tests/polars/timezones.py
new file mode 100644
index 0000000000..62b830df5c
--- /dev/null
+++ b/marimo/_smoke_tests/polars/timezones.py
@@ -0,0 +1,50 @@
+import marimo
+
+__generated_with = "0.11.18"
+app = marimo.App(width="medium")
+
+
+def _():
+ from datetime import datetime
+ import pytz
+ import polars as pl
+
+ df = pl.DataFrame(
+ {
+ "tz_utc": [datetime(2010, 10, 7, 5, 15, tzinfo=pytz.UTC)],
+ "no_tz": [datetime(2010, 10, 8, 5, 15)],
+ }
+ ).with_columns(
+ tz_america=pl.col("no_tz").dt.replace_time_zone("America/New_York"),
+ tz_asia=pl.col("no_tz").dt.replace_time_zone("Asia/Tokyo"),
+ )
+ return datetime, df, pl, pytz
+
+
+def _(df):
+ df
+ return
+
+
+def _(df, mo):
+ mo.plain(df)
+ return
+
+
+def _(df):
+ df.to_dicts()
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()