Monday, March 26, 2018

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

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


On Sunday, March 25, 2018 at 10:51:25 AM UTC-6, Nirmal Raghavan wrote:
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'      )  )

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/60231531-06ac-45fc-b319-5af780a4c429%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment