Unlisted
Edited
Oct 22, 2023
Insert cell
Insert cell
// Create data to work with
data = d3.range(10).map(d => {
const date = d3.utcDay.offset(new Date(), -d) // JavaScript date object
const stringDate = date.toISOString() // String version of the date
return {date, stringDate}
})
Insert cell
Insert cell
data
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
Insert cell
data
select *, CAST(stringDate as timestamp) as dateTime from data
Insert cell
Insert cell
// Create data to work with
data2 = d3.range(10).map(d => new Date(+d3.utcDay() + d))
Insert cell
data2
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
data2
select * from data2
Insert cell
Insert cell
Insert cell
{
const date = new Date("2023-02-01T12:34:56Z");
const duckdb = await import(`https://cdn.observableusercontent.com/npm/@duckdb/duckdb-wasm@${version.duckdb}/+esm`);
// The version specifier for apache-arrow must precisely match the one that
// duckdb-wasm references, otherwise importing arrow tables will fail.
const arrow = await import(`https://cdn.observableusercontent.com/npm/apache-arrow@${version.arrow}/+esm`);

const db = await initDB(duckdb);
const conn = await db.connect();
const table = arrow.tableFromJSON([{date}]);
await conn.insertArrowTable(table, {name: "t"});

const result = toJSON(await conn.query("select date d from t"))[0].d;
conn.close();
const type = table.schema.fields[0].type;
return {result, type, typeId: type.typeId};

// https://observablehq.slack.com/archives/C01N0F9GPHV/p1697567980431419?thread_ts=1697567115.347619&cid=C01N0F9GPHV
async function initDB(duckdb) {
const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
const workerUrl = URL.createObjectURL(new Blob([`importScripts("${bundle.mainWorker}");`], {type: "text/javascript"}));
const worker = new Worker(workerUrl);
const logger = new duckdb.ConsoleLogger();
const db = new duckdb.AsyncDuckDB(logger, worker);
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
URL.revokeObjectURL(workerUrl);
return db;
}

function toJSON(result) {
return result.toArray().map(row => row.toJSON());
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more