Sabbiu Shah
Sabbiu Shah

Reputation: 1709

Filter data for a given day (timezone aware datetime) from postgres directly

I want to filter all data for the following day (which is timezone aware).

Assumptions:

My current approach is:

date = received_date_timezone_aware # any time of that day
lower = date.replace(hour=0,minute=0,second=0)
upper = lower + datetime.timedelta(day=1)

data = Model.objects.filter(date__gte=lower, date__lt=upper)

Question

Is there a direct solution to this using django orm or raw query?

Note: I wanted to know if there is a better way which can save me a few lines of code of manipulating the datetime myself

Upvotes: 0

Views: 193

Answers (1)

schillingt
schillingt

Reputation: 13731

No, there isn't. However what you're doing isn't the best way to do it either as using replace can result in some oddities with day lights savings. I'd recommend using lower = received_date_timezone_aware.date().

This assumes Model.date is a DateField. If it's a datetime, then do this:

from datetime import time, datetime

def min_datetime(date: datetime, tz):
    """Get the min datetime of the given datetime and timezone.

    :return datetime: Minimum datetime of the given date.
    """
    return tz.localize(
        datetime.combine(date.astimezone(tz).date(), time.min))


def max_datetime(date: datetime, tz):
    """Get the max datetime of the given datetime and timezone.

    :return datetime: Maximum datetime of the given date.
    """
    return tz.localize(
        datetime.combine(date.astimezone(tz).date(), time.max))

Model.objects.filter(date__range=(min_datetime(value, tz), max_datetime(value, tz)))

Upvotes: 2

Related Questions