2

Im new to python and trying to insert the date/time into my firebase.put Im unsure of what this should be and would appreciate some help. Ive tried this, strip() and a couple other unsuccessful things. Please help! Thank you

from firebase import firebase
import time
import datetime

whattime = datetime.datetime.now()
firebase = firebase.FirebaseApplication('my_firebase_link',None)

result = firebase.put('/user',str(whattime),'testing')
WannaBePyGuy
  • 29
  • 1
  • 3

2 Answers2

0

There are 2 approaches for timestamps in Firebase, the local machine one and Firebase's own timestamp, the following examples demonstrate each one.

Both examples will require to import the following modules:

import urllib.request
import urllib.error
import json
import time #For the first example only

In this example we use the built in time module from Python (the datetime module works the same). The value from time.time() will be stored as a float and you should convert it back into a date object when you read it back from Firebase.

def send_message(message, username):

    my_data = dict()
    my_data["message"] = message
    my_data["username"] = username
    my_data["timestamp"] = time.time()

    json_data = json.dumps(my_data).encode()

    try:
        loader = urllib.request.urlopen("https://<YOUR-PROJECT-ID>.firebaseio.com/messages.json", data=json_data)
    except urllib.error.URLError as e:
        message = json.loads(e.read())
        print(message["error"])
    else:
        print(loader.read())

This example will use Firebase internal timestamp. The value {".sv": "timestamp"} is interpreted by Firebase and it's converted into a timestamp when the request is processed.

def send_message(message, username):

    my_data = dict()
    my_data["message"] = message
    my_data["username"] = username
    my_data["timestamp"] = {".sv": "timestamp"}

    json_data = json.dumps(my_data).encode()

    try:
        loader = urllib.request.urlopen("https://<YOUR-PROJECT-ID>.firebaseio.com/messages.json", data=json_data)
    except urllib.error.URLError as e:
        message = json.loads(e.read())
        print(message["error"])
    else:
        print(loader.read())
Mr. Phantom
  • 482
  • 3
  • 11
0

This code solved the problem for me:

import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("/home/pi/Documents/gpioZero/iot-maison-firebase- adminsdk-a0c7t-666fdeb9bd.json")
firebase_admin.initialize_app(cred)

db = firestore.client()
pir = MotionSensor(4)
led = LED(16)

def motionOn():
    doc_ref = db.collection(u'motion').document(u'test1')
    dateNow = datetime.datetime.now() 
    doc_ref.set({u'started': True,u'date': dateNow })
    led.on()
    print("On")
pir.when_activated=motionOn
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61