Ihar
Ihar

Reputation: 185

Get items for the last few hours

In the model there is a field DateTimeField(), the database stores the value of the form 2015-09-21 17:37:11. How to make a selection, for the last several hours. For example, in the sample were only the values for the last 3 hours.

Upvotes: 1

Views: 69

Answers (2)

Gocht
Gocht

Reputation: 10256

Try:

from datetime import datetime, timedelta

delta = datetime.now() - timedelta(hours=3)
Model.objects.filter(date_time__gte=delta)

Upvotes: 0

spectras
spectras

Reputation: 13562

You need to build the date reference manually, and use it in the query.

from datetime import datetime, timedelta

now = datetime.now()
before = now - timedelta(hours=3)

qs = MyModel.objects.filter(date__gte=before)

As a reference, the datetime module. Note that if you use locale-aware times in your application (through USE_TZ=True setting), you will need to change the way you get current time to this:

from django.utils import timezone
now = timezone.now()

Upvotes: 1

Related Questions