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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: clearer dates and datetimes with utc (#2799)
Myles Scolnick06ea8365545e
diff --git a/frontend/src/components/data-table/chart-spec-model.tsx b/frontend/src/components/data-table/chart-spec-model.tsxindex 94f001a172..444c7395f1 100644--- a/frontend/src/components/data-table/chart-spec-model.tsx+++ b/frontend/src/components/data-table/chart-spec-model.tsx@@ -4,6 +4,7 @@ import { mint, orange, slate } from "@radix-ui/colors";import type { ColumnHeaderSummary, FieldTypes } from "./types";import { asURL } from "@/utils/url";import { parseCsvData } from "@/plugins/impl/vega/loader";+import { logNever } from "@/utils/assertNever";const MAX_BAR_HEIGHT = 24; // pxconst MAX_BAR_WIDTH = 28; // px@@ -88,6 +89,8 @@ export class ColumnChartSpecModel<T> {switch (type) {case "date":+ case "datetime":+ case "time":return {...base,mark: {@@ -108,7 +111,12 @@ export class ColumnChartSpecModel<T> {{field: column,type: "temporal",- format: "%Y-%m-%d",+ format:+ type === "date"+ ? "%Y-%m-%d"+ : type === "time"+ ? "%H:%M:%S"+ : "%Y-%m-%dT%H:%M:%S",bin: true,title: column,},@@ -241,6 +249,7 @@ export class ColumnChartSpecModel<T> {case "string":return null;default:+ logNever(type);return null;}}diff --git a/frontend/src/components/data-table/column-summary.tsx b/frontend/src/components/data-table/column-summary.tsxindex 37ff69e00f..1aa11daaf6 100644--- a/frontend/src/components/data-table/column-summary.tsx+++ b/frontend/src/components/data-table/column-summary.tsx@@ -6,6 +6,8 @@ import { prettyNumber, prettyScientificNumber } from "@/utils/numbers";import { prettyDate } from "@/utils/dates";import { DelayMount } from "../utils/delay-mount";import { ChartSkeleton } from "../charts/chart-skeleton";+import { logNever } from "@/utils/assertNever";+import { DatePopover } from "./date-popover";export const ColumnChartContext = React.createContext<ColumnChartSpecModel<unknown>@@ -25,7 +27,6 @@ export const TableColumnSummary = <TData, TValue>({const chartSpecModel = useContext(ColumnChartContext);const { theme } = useTheme();const { spec, type, summary } = chartSpecModel.getHeaderSummary(columnId);-let chart: React.ReactNode = null;if (spec) {chart = (@@ -45,6 +46,17 @@ export const TableColumnSummary = <TData, TValue>({);}+ const renderDate = (+ date: string | number | null | undefined,+ type: "date" | "datetime",+ ) => {+ return (+ <DatePopover date={date} type={type}>+ {prettyDate(date, type)}+ </DatePopover>+ );+ };+const renderStats = () => {if (!summary) {return null;@@ -52,12 +64,13 @@ export const TableColumnSummary = <TData, TValue>({switch (type) {case "date":+ case "datetime":// Without a chartif (!spec) {return (<div className="flex flex-col whitespace-pre">- <span>min: {prettyDate(summary.min)}</span>- <span>max: {prettyDate(summary.max)}</span>+ <span>min: {renderDate(summary.min, type)}</span>+ <span>max: {renderDate(summary.max, type)}</span><span>unique: {prettyNumber(summary.unique)}</span><span>nulls: {prettyNumber(summary.nulls)}</span></div>@@ -66,8 +79,8 @@ export const TableColumnSummary = <TData, TValue>({return (<div className="flex justify-between w-full px-2 whitespace-pre">- <span>{prettyDate(summary.min)}</span>-- <span>{prettyDate(summary.max)}</span>+ <span>{renderDate(summary.min, type)}</span>-+ <span>{renderDate(summary.max, type)}</span></div>);case "integer":@@ -132,6 +145,8 @@ export const TableColumnSummary = <TData, TValue>({<span>nulls: {prettyNumber(summary.nulls)}</span></div>);+ case "time":+ return null;case "string":return (<div className="flex flex-col whitespace-pre">@@ -145,6 +160,9 @@ export const TableColumnSummary = <TData, TValue>({<span>nulls: {prettyNumber(summary.nulls)}</span></div>);+ default:+ logNever(type);+ return null;}};diff --git a/frontend/src/components/data-table/date-popover.tsx b/frontend/src/components/data-table/date-popover.tsxnew file mode 100644index 0000000000..c38994438e--- /dev/null+++ b/frontend/src/components/data-table/date-popover.tsx@@ -0,0 +1,119 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React from "react";+import { Tooltip } from "@/components/ui/tooltip";++interface DatePopoverProps {+ date: Date | string | number | null | undefined;+ type: "date" | "datetime";+ children: React.ReactNode;+}++export const DatePopover: React.FC<DatePopoverProps> = ({+ date,+ type,+ children,+}) => {+ // Return just the text if date is invalid+ if (!date || Number.isNaN(new Date(date).getTime())) {+ return children;+ }++ const dateObj = new Date(date);+ const relativeTime = getRelativeTime(dateObj);++ const content = (+ <div className="min-w-[240px] p-1 text-sm">+ <div className="text-muted-foreground mb-2">{relativeTime}</div>+ <div className="space-y-1">+ {type === "datetime" ? (+ Object.entries(getTimezones(dateObj)).map(+ ([timezone, formattedDate]) => (+ <div+ key={timezone}+ className="grid grid-cols-[fit-content(40px),1fr] gap-4 items-center justify-items-end"+ >+ <span className="bg-muted rounded-md py-1 px-2 w-fit ml-auto">+ {timezone}+ </span>+ <span>{formattedDate}</span>+ </div>+ ),+ )+ ) : (+ <span>+ {dateObj.toLocaleDateString("en-US", {+ timeZone: "UTC",+ dateStyle: "long",+ })}+ </span>+ )}+ </div>+ </div>+ );++ return (+ <Tooltip content={content} delayDuration={200}>+ <span>{children}</span>+ </Tooltip>+ );+};++function getTimezones(date: Date) {+ const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return {+ UTC: new Intl.DateTimeFormat("en-US", {+ timeZone: "UTC",+ dateStyle: "long",+ timeStyle: "medium",+ }).format(date),+ [localTimezone]: new Intl.DateTimeFormat("en-US", {+ timeZone: localTimezone,+ dateStyle: "long",+ timeStyle: "medium",+ }).format(date),+ };+}++/**+ * Converts a date into a human-readable relative time string (e.g. "2 hours ago", "in 5 minutes")+ * Uses Intl.RelativeTimeFormat for localized formatting+ */+function getRelativeTime(date: Date): string {+ // Initialize relative time formatter with English locale and "auto" numeric style+ // "auto" allows for strings like "yesterday" instead of "1 day ago"+ const relativeTimeFormatter = new Intl.RelativeTimeFormat("en", {+ numeric: "auto",+ });++ const currentTime = new Date();+ // Get difference in seconds between now and the input date+ const differenceInSeconds = (currentTime.getTime() - date.getTime()) / 1000;++ // Define time units with their thresholds and conversion factors+ // Format: [threshold before next unit, seconds in this unit, unit name]+ const timeUnits: Array<[number, number, string]> = [+ [60, 1, "second"], // Less than 60 seconds+ [60, 60, "minute"], // Less than 60 minutes+ [24, 3600, "hour"], // Less than 24 hours+ [365, 86_400, "day"], // Less than 365 days+ [Number.POSITIVE_INFINITY, 31_536_000, "year"], // Everything else in years+ ];++ // Find the appropriate unit to use+ for (const [unitThreshold, secondsInUnit, unitName] of timeUnits) {+ const valueInUnits = differenceInSeconds / secondsInUnit;++ if (valueInUnits < unitThreshold) {+ // Convert to fixed decimal and negate since RelativeTimeFormat expects+ // negative values for past times and positive for future times+ const roundedValue = -Number(valueInUnits.toFixed(1));+ return relativeTimeFormatter.format(+ roundedValue,+ unitName as Intl.RelativeTimeFormatUnit,+ );+ }+ }++ // Should never reach here due to Infinity threshold, but provide fallback+ return relativeTimeFormatter.format(0, "second");+}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 2d36a8598c..3b7b35a1bd 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -330,7 +330,7 @@ export const LoadingDataTableComponent = memo(search,filters,searchQuery,- props.fieldTypes,+ useDeepCompareMemoize(props.fieldTypes),props.data,paginationState.pageSize,paginationState.pageIndex,diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.tsindex 8e275c0645..2be5ad4c62 100644--- a/frontend/src/plugins/impl/vega/loader.ts+++ b/frontend/src/plugins/impl/vega/loader.ts@@ -108,8 +108,7 @@ export async function vegaLoadData<T = object>(middleware.push(BIG_INT_MIDDLEWARE);}- // Apply middleware- const unsubscribes = middleware.map((m) => m());+ let unsubscribes: Unsubscribe[] = [];// Load the datatry {@@ -162,6 +161,8 @@ export async function vegaLoadData<T = object>(});}+ // Apply middleware+ unsubscribes = middleware.map((m) => m());// Always set parse to auto for csv data, to be able to parse dates and floatsconst results = isCsv? // csv -> jsondiff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.tsindex 20dc4f0438..49fb23061f 100644--- a/frontend/src/utils/dates.ts+++ b/frontend/src/utils/dates.ts@@ -1,12 +1,23 @@/* Copyright 2024 Marimo. All rights reserved. */import { Logger } from "./Logger";-export function prettyDate(value: string | number | null | undefined): string {+export function prettyDate(+ value: string | number | null | undefined,+ type: "date" | "datetime",+): string {if (value == null) {return "";}try {+ // If type is date, drop the timezone by rendering in UTC+ // since dates are absolute+ if (type === "date") {+ value = new Date(value).toLocaleDateString(undefined, {+ timeZone: "UTC",+ });+ }+return new Date(value).toLocaleDateString(undefined, {year: "numeric",month: "short",diff --git a/marimo/_smoke_tests/timezones.py b/marimo/_smoke_tests/timezones.pynew file mode 100644index 0000000000..305a8d01b0--- /dev/null+++ b/marimo/_smoke_tests/timezones.py@@ -0,0 +1,54 @@+import marimo++__generated_with = "0.9.14"+app = marimo.App(width="medium")+++def __():+ import polars as pl+ from datetime import datetime, date, time+ import marimo as mo++ df = pl.DataFrame(+ {+ "price": [40, 50],+ "datetime": [datetime(2020, 1, 1), datetime(2020, 1, 2)],+ }+ )+ df+ return date, datetime, df, mo, pl, time+++def __(df, pl):+ df.with_columns(pl.col("datetime").dt.replace_time_zone("Asia/Kathmandu"))+ return+++def __(date, pl):+ df2 = pl.DataFrame(+ {+ "price": [40, 50],+ "date": [date(2020, 1, 1), date(2020, 1, 2)],+ }+ )+ df2+ return (df2,)+++def __(pl, time):+ df3 = pl.DataFrame(+ {+ "price": [40, 50],+ "time": [time(1, 30), time(2, 30)],+ }+ )+ df3+ return (df3,)+++if __name__ == "__main__":+ app.run()