marcoslhc
marcoslhc

Reputation: 1194

How to list all the objects with a specific date no matter the time in a DateTime Field

I Have a model like this

foo=models.char
bar=models.dateime

In wich several foos arrives in one day in different time. I need to list all the foos in a specific date, no matter the time they arrive. I can't change the model, so splitting the bar in two fields(one for date and one for time) is out of reach right now :(

Upvotes: 0

Views: 86

Answers (2)

Jack M.
Jack M.

Reputation: 32070

I personally used the range filter and the internal datetime timestamps for max/min. For example:

date = datetime.date.today()
YourModel.objects.filter(bar__range=(
                                datetime.datetime.combine(
                                        date,
                                        datetime.time.min
                                    ),
                                datetime.datetime.combine(
                                        date,
                                        datetime.time.max
                                    ),
                            ))

Upvotes: 2

Jean
Jean

Reputation: 21595

Assuming a datetime format like so : YYYYMMDD HHmmss eg : 20100611 171000 would be the 11th of June 1020, 5:10pm

Assuming a list of models with the following dates: 20100609 120000 20100611 161204 20100611 121204 20100611 191204

And you want all models for 20100611, in pseudo-code you could do :

for (model in models) 
  if (model.datetime >='20100611 000000' or model.datetime<='20100611 235959')
    filtered_foos.add(model.foo)

This will effecttively ignore the time part of the date (sorry I don't have a python interpreter the syntax is clearly off but you should get the idea)

Upvotes: 0

Related Questions