$date in collections
-
Python
-
TypeScript
-
Java
-
curl
The handling of datetime objects changed in Python client version 2.0. DataStax recommends upgrading to the latest version of the Python client. For more information, see Data API client upgrade guide. |
The Python client provides the DataAPITimestamp
and DataAPIDate
objects for storing dates.
However, if you insert a document with a DataAPIDate
value, the client will always return DataAPITimestamp
.
DataStax recommends that you use DataAPITimestamp
instead of DataAPIDate
for collections since equality filters on DataAPIDate
may not behave as expected if the implicit conversion to DataAPITimestamp
uses a different timezone than expected.
The DataAPITime
and DataAPIDuration
objects can’t be used with collections.
For more information, see Python client usage: Client custom data types.
The Python client also supports standard-library date
and datetime
.
If you use a standard-library datetime
that is not timezone-aware (or just a date
, which is always timezone-naive), the client will raise an error by default.
For more information, see Python client usage: DataAPITimestamp and datetimes.
from astrapy import DataAPIClient
from astrapy.data_types import DataAPITimestamp
from datetime import datetime
# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")
# Insert documents containing timestamp values
collection.insert_one(
{"when": DataAPITimestamp.from_string("2024-12-06T12:34:56.789Z")}
)
collection.insert_one({"registered_at": DataAPITimestamp.from_datetime(datetime.datetime.now())})
# Update a document, using a timestamp in the filter:
collection.update_one(
{"registered_at": DataAPITimestamp.from_string("2024-12-06T12:34:56.789Z")},
{"$set": {"message": "happy Sunday!"}},
)
# Update a document, setting "last_reviewed" to the current date:
collection.update_one(
{"registered_at": {"$exists": True}},
{"$currentDate": {"last_reviewed": True}},
)
# Find documents by inequality on a timestamp value:
print(
collection.find_one(
{
"registered_at": {
"$lt": DataAPITimestamp.from_string("2025-12-06T12:34:56.789Z")
}
},
projection={"_id": False},
)
)
# will print something like:
# {'registered_at': DataAPITimestamp(timestamp_ms=1733488496789 [2024-12-06T12:34:56.789Z])}
You can use standard JS Date
objects anywhere in documents to represent dates and times.
Read operations also return Date
objects for document fields stored using { $date: number }
.
The following example uses dates in insert
, update
, and find
commands:
import { DataAPIClient } from '@datastax/astra-db-ts';
// Reference an untyped collection
const client = new DataAPIClient('TOKEN');
const db = client.db('ENDPOINT', { keyspace: 'KEYSPACE' });
(async function () {
// Create an untyped collection
const collection = await db.createCollection('dates_test');
// Insert documents with some dates
await collection.insertOne({ dateOfBirth: new Date(1394104654000) });
await collection.insertOne({ dateOfBirth: new Date('1863-05-28') });
// Update a document with a date and setting lastModified to now
await collection.updateOne(
{
dateOfBirth: new Date('1863-05-28'),
},
{
$set: { message: 'Happy Birthday!' },
$currentDate: { lastModified: true },
},
);
// Will print around new Date()
const found = await collection.findOne({ dateOfBirth: { $lt: new Date('1900-01-01') } });
console.log(found?.lastModified);
})();
The Data API uses the ejson
standard to represents time-related objects.
The Java client introduces custom serializers as three types of objects: java.util.Date
, java.util.Calendar
, java.util.Instant
.
You can use these objects in documents as well as filter clauses and update clauses.
The following example uses dates in insert
, update
, and find
commands:
package com.datastax.astra.client.collections;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.core.query.Projection;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import static com.datastax.astra.client.collections.commands.Updates.set;
import static com.datastax.astra.client.core.query.Filters.eq;
import static com.datastax.astra.client.core.query.Filters.lt;
public class WorkingWithDates {
public static void main(String[] args) {
// Given an existing collection
Collection<Document> collection = new DataAPIClient("TOKEN")
.getDatabase("API_ENDPOINT")
.getCollection("COLLECTION_NAME");
Calendar c = Calendar.getInstance();
collection.insertOne(new Document().append("registered_at", c));
collection.insertOne(new Document().append("date_of_birth", new Date()));
collection.insertOne(new Document().append("just_a_date", Instant.now()));
collection.updateOne(
eq("registered_at", c), // filter clause
set("message", "happy Sunday!")); // update clause
collection.findOne(
lt("date_of_birth", new Date(System.currentTimeMillis() - 1000 * 1000)),
new CollectionFindOneOptions().projection(Projection.exclude("_id")));
}
}
You can use $date
to represent dates as Unix timestamps in the JSON payload of a Data API command:
"date_of_birth": { "$date": 1690045891 }
The following example includes a date in an insertOne
command:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"insertOne": {
"document": {
"$vector": [0.25, 0.25, 0.25, 0.25, 0.25],
"date_of_birth": { "$date": 1690045891 }
}
}
}' | jq
The following example uses the date to find and update a document with the updateOne
command:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"updateOne": {
"filter": {
"date_of_birth": { "$date": 1690045891 }
},
"update": { "$set": { "message": "Happy birthday!" } }
}
}' | jq
The following example uses the $currentDate
update operator to set a property to the current date:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOneAndUpdate": {
"filter": { "_id": "doc1" },
"update": {
"$currentDate": {
"createdAt": true
}
}
}
}' | jq