Jack tileman
Jack tileman

Reputation: 871

Python query against firestore.SERVER_TIMESTAMP field

We have a Python (3.6) application and are using Firestore.

The field is called timestamp_date and it has the value of firestore.SERVER_TIMESTAMP

We use this field for paginated query. One of the query that we have is

query_docs =  query_forward.start_at({
    u'timestamp_date' : input_date_variable
}).stream()

The value of input_date_variable is "2022-08-24T04:57:17.065000+00:00". How can we convert input_date_variable to a format of firestore.SERVER_TIMESTAMP so the query works? Currently the query does not work.

Upvotes: 0

Views: 83

Answers (1)

Marc Anthony B
Marc Anthony B

Reputation: 4079

You have to use Epoch or UNIX time to query against the firestore.SERVER_TIMESTAMP. By being said, you have to convert the value(if the value is a string) to datetime and then convert it to Epoch time. See code below:

import time
from datetime import datetime

input_date_variable = '2022-08-24T04:57:17.065000+00:00'

d = datetime.strptime(input_date_variable, "%Y-%m-%dT%H:%M:%S.%f%z")
d = time.mktime(d.timetuple()) * 1000

query_forward = db.collection(u'collection')
query_docs =  query_forward.order_by(u'timestamp_date').start_at({
    u'timestamp_date' : d
}).stream()

for doc in query_docs:
  print(f'{doc.id} => {doc.to_dict()}')

Also, I would like to point out your query which will return an error. All fields in the cursor must come from fields set in order_by().

For more information, you may check out this documentation.

Upvotes: 1

Related Questions