pythonprismaprisma-binding

How to set DateTime field in prisma python client


I'm struggling to find a way to create a db entry in python Prisma client for a model with a DateTime field i.e.

model Device {
  id          Int      @id @default(autoincrement())
  name        String
  timestamp   DateTime

}

In my python program using prisma client

from datetime import datetime
from prisma import Prisma

# ... other code that ends up with e["timestamp"] with a UNIX timestamp like 1692041472000
timestamp = datetime.fromtimestamp(int(e["timestamp"]/1000))
device_obj = {
    "name": e["name"],
    "timestamp": timestamp,
}
device_db = await self.db.device.create(device_obj)

this results in Invalid argument type. timestampshould be of any of the following types:DateTime`,

In the generated prisma/model.py there is

class Device(bases.BaseDevice):
    """Represents a Device record"""

    id: _int
    name: _str
    timestamp: datetime.datetime

I don't see mentioned anywhere how to properly create an object that can be serialized as DateTime.

I'm wonder if is worth dealing with DateTime given there are problem also serializing it back to json

Some background: I'm using Prisma client both in python and js. backend python writes to db the frontend get notified and reads data back. My Svelte frontend have API endpoints so I need to serialize in json but also work with those timestamp comparing dates in my queries etc

What's my best shot? Store all to string and convert it back and forth?


Solution

  • Since datetime.utcfromtimestamp() has been deprecated, this worked for me datetime.combine(date.today(), datetime.min.time()).isoformat() + 'Z'