Converting a datetime to a date in database

Continuing the discussion from Search inside Dict:

The Cast function from python-sql can be used to convert from datetime (or timestampt) to date:

>>> from sql import Table, Cast
>>> t = Table('a')
>>> tuple(t.select(Cast(t.date, 'DATE')))
('SELECT CAST("a"."date" AS DATE) FROM "a" AS "a"', ())

In tryton you can use sql_type function to determine the database type used to represent a field.

So inside tryton you can use:

Model = Pool().get('model.name')
table = Model.__table__()
table.select(Cast(table.datetime, Model.date.sql_type().base)              

To select the value of the datetime field converted to the date field sql type.

Hope it helps

1 Like

Hi. I am trying to make this work, but I am constantly failing. A little help please
I have a datetime field, name first_contact on a model named contact_tracing. So according to the previous answer, to cast it like a date type, I would have to make something like this.

ContactTracing = Pool().get('contact_tracing')
table = ContactTracing.__table__()
query0 = table.select(Cast(table.first_contact.datetime, ContactTracing.date.sql_type().base))

Obviously I am doing something wrong.

You should use table.first_contact to select the first_contact column instead of table.first_contact.datetime and you should use the name of a date field instead of ‘date’ in the second part of the cast

1 Like

It could be any field from any table, right? It just needs to be a date field

Yes, any date field is valid for the cast