Python datetime.replace() has unexpected behaviour when uploading to Firebase Firestore

42 Views Asked by At

For testing purposes, I have deployed the following Firebase Cloud Function. When the function gets called, it adds a document to my Firestore collection with two fields containing two datetimes.

@https_fn.on_call(region='europe-west1', vpc_connector='connector1', vpc_connector_egress_settings=options.VpcEgressSetting('ALL_TRAFFIC'))
def testing(req: https_fn.CallableRequest):
    firestore_client: google.cloud.firestore.Client = firestore.client()
    visit_collection = firestore_client.collection('visits')
    visit_collection.add(
        {
            'test1': datetime.now().astimezone(),
            'test2': datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).astimezone(),
        },
        'test'
    )

When looking at the contents of the document in Cloud Firestore in the Firebase Console, what I would expect for the values of the fields in my document is (if it would be 19:50):

test1: 23 March 2024 at 19:50:00 UTC+1
test2: 23 March 2024 at 00:00:00 UTC+1

Instead, what I see in the document is:

test1: 23 March 2024 at 19:50:00 UTC+1
test2: 23 March 2024 at 01:00:00 UTC+1
1

There are 1 best solutions below

1
jaakdentrekhaak On

I avoided the problem using the pytz package:

import pytz
from datetime import datetime, time
from firebase_functions import https_fn, options
from firebase_admin import initialize_app, auth, firestore
import google.cloud.firestore

@https_fn.on_call(region='europe-west1', vpc_connector='connector1', vpc_connector_egress_settings=options.VpcEgressSetting('ALL_TRAFFIC'))
def testing(req: https_fn.CallableRequest):
    firestore_client: google.cloud.firestore.Client = firestore.client()
    visit_collection = firestore_client.collection('visits')
    brussels_tz = pytz.timezone('Europe/Brussels')
    current_datetime = datetime.now(brussels_tz)
    current_date = current_datetime.date()
    midnight_brussels = datetime.combine(current_date, time())
    midnight_brussels = brussels_tz.localize(midnight_brussels)
    visit_collection.add(
        {
            'test1': current_datetime,
            'test2': midnight_brussels,
        },
        'test'
    )