How to combine a custom date and time field in Django?

329 views
Skip to first unread message

Nirmal Raghavan

unread,
Mar 25, 2018, 12:51:25 PM3/25/18
to Django users
I'm looking for a way to combine a custom date value and a time field in django. My model only contains a time field. Now I have to annotate a new field combining a custom date and the time field. I thought the following code will slve my problem, but it only gives the date value. TimeField is ignored.

Please advise the right way to solve this issue.

class MyModel(models.Model):
   my_time_field = TimeField()

custom_date = datetime.today().date()
objects = MyModel.objects.annotate(
    custom_datetime=Func(
        custom_date + F('my_time_field'),
        function='DATE'
    )
)

hunter...@gmail.com

unread,
Mar 26, 2018, 10:44:18 AM3/26/18
to Django users
Using database time functions is a bit of a hassle since each database seems to have its own syntax for these types.
If you are using MySQL, the function you are calling will only return a DATE field, in this case you want to use TIMESTAMP with the parameters all combined in a single text string.  See:  https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestamp

For SQLite, you would use datetime, see: https://www.sqlite.org/lang_datefunc.html

For PostgreSQL, you would use make_timestamp, see https://www.postgresql.org/docs/10/static/functions-datetime.html

Assuming you are using MySQL, I think your code should look like this (not tested):

class MyModel(models.Model):
   my_time_field = TimeField()


custom_date = datetime.date.today()  # note the correct calling sequence
objects = MyModel.objects.annotate(
    custom_datetime=Func(
        custom_date.isoformat() + ' ' + F('my_time_field'),
        function='TIMESTAMP'
    )
)
Reply all
Reply to author
Forward
0 new messages