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())