How can I implement a scheduled function in Python using Firebase to delete a document from Firestore? I’ve successfully set up the function, but when I attempt to add a condition based on the ‘endDate’ field, which is of type Timestamp, the function fails to execute properly. Can anyone provide insights or suggestions on how to handle Timestamp fields within Firebase scheduled functions for Python?
@scheduler_fn.on_schedule(schedule="every hour")
def check_end_date(context):
id = "static-id"
doc_ref = db.collection("name").document(id)
try:
doc = doc_ref.get()
if doc.exists:
doc_data = doc.to_dict()
end_date = doc_data.get('endDate')
# Get current timestamp
current_time = datetime.datetime.now().timestamp()
# Extract seconds and nanoseconds from end_date Timestamp
end_date_seconds = end_date.seconds
end_date_nanos = end_date.nanos
# Combine seconds and nanoseconds into a single value
end_date_combined = end_date_seconds + end_date_nanos / 1e9
if current_time > end_date_combined:
doc_ref.delete()
functions.logger.info(f"Ad document '{id}' deleted successfully.")
else:
functions.logger.info(f"Ad document '{id}' still valid.")
else:
functions.logger.warning(f"Ad document '{id}' does not exist.")
except NotFound:
functions.logger.error(f"Ad document '{id}' not found.")
2
Answers
I finally solved it.
If you want to perform programmatic comparisons between Timestamp types using Python, refer to the Timestamp API documentation.
Every timestamp has seconds and nanos number properties which together represent the point in time of the timestamp. You can write code to compare these values to implement your condition.