'Strange! python datetime.datetime.now() randomly generate unix second and nanosecond timestamp
I have deployed a GCP cloud function that updates Firestore time_created and time_updated fields in Firestore. My front-end app first creates these fields in Firestore but my function updates them after processing the documents. A snippet of code below generates the timestamp and I use Firestore update function to update the document. There are a few instances where the fields in Firestore will be updated as a dictionary with keys as "seconds" and "nano_seconds" and their values but not as Timestamp. I have been wondering and trying to track down where the issue is coming from. I suspect datetime.now() sometimes does not generate a timestamp value. Help me if you have an idea or seen something like this before. I have attached a snapshot below. The image attached shows an instance of the wrongly formatted date returned from Firestore to my Front-end.
Documents affected have the field showing as this:
time_created: {'seconds': 1637694047.0, 'nanoseconds': 580592000.0}
from datetime import datetime
update_doc = {
u"time_created": datetime.now(),
u"time_updated": datetime.now()
}
Solution 1:[1]
Per @mark-tolonen, please don't include images in questions when it's trivial to copy-and-paste the test. Various reasons.
I experienced a different issue with Firestore timestamps and using the Go SDK. When I read your question, I wondered if the issues were related but, I think not.
That said, you can perform some diagnosis. You can emit the Python datetime.now() values of course to ensure you know what's being applied.
You could (!) then use the underlying REST API directly to mimic|repro the calls that your code is making to determine whether the error arises in the API itself or the Python SDK (or your code).
Here's projects.databases.documents.patch which I think underlies the Set. There's also projects.databases.documents.create. In both cases, APIs Explorer provides a way for you to try the API methods in the browser and will yield the e.g. curl equivalents for you.
NOTE
The API requires a
parentparameter, defined to be something of the formprojects/{project_id}/databases/{databaseId}/documents. Replaceproject_idwith your Project ID and use(default)(with the parenthesis) for the value of{databaseId}.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DazWilkin |
