0

I am trying to filter by time to delete messages from an sqlite3 database. I am taking a string that is accurate to the minute, converting that to a datetime object, and using the filter function on the QuerySet of messages. However, the entry in the database is far more precise than the string, so the message I'm looking for is being filtered out as well.

I'm automatically generating the datetime object using

class Message(models.Model):
    ....
    time = models.DateTimeField(auto_now_add=True)

I'm filtering using

Message.objects.all().filter(time=time)

For example, the string I'm using to create the datetime object to filter is 'Dec. 5, 2015, 5:07 PM' to create a datetime object '2015-12-05 05:07:00'. However, the message I'm looking for is from time '2015-12-05 17:07:19.308321'

Is there an option to make the auto-generated datetime objects less precise, to the minute instead of fraction of a second?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
NateTheGreat
  • 33
  • 2
  • 6
  • Don't think so, but you could probably filter between target datetime and next minute. – Lorenzo Peña Dec 05 '15 at 19:56
  • Also, if you are willing to use a custom model field, subclass `DateTimeField` and override `pre_save`. There you could calculate `timezone.now()` and reduce the precision. – Lorenzo Peña Dec 05 '15 at 20:08
  • Just an observation: hoping that two real-world datetime objects will ever be exactly, bit-for-bit, equal to one another ls like hoping that two floating point numbers will be equal. It they are, it's a lucky accident. You need to use ranges of time values rather than equality, in general. – O. Jones Dec 07 '15 at 11:48
  • you could save [rounded datetime values](http://stackoverflow.com/q/32723150/4279) – jfs Dec 08 '15 at 19:46

0 Answers0