Search code examples
pythondjangodatetimedjango-timezone

how to get records for a day relative to timezone in django


I am trying to all the record for a certain day with the following:

entered_at = request.session['entered_at']
entered_at = datetime.strptime(entered_at, "%m-%d-%Y")
day_start = entered_at.replace(hour=00, minute=00)
day_end = entered_at.replace(hour=23, minute=59)

entries = Entry.objects.filter(
                                                  customer=customer, 
                                                  entered_at__lt=day_end, 
                                                  entered_at__gte=day_start
                                                  )

When I do this I get the following warning in my console:

DateTimeField received a naive datetime while time zone support is active.

I know I can add something like: , day_start = entered_at.replace(hour=00, minute=00, tzinfo=<UTC>)

however, this will not make the range from midnight to 11:59pm relative to the users timezone if I use UTC.

How can I express a full day relative to the users timezone?


Solution

  • I believe you want something like this, using the pytz library. See How to make an unaware datetime timezone aware in python:

    import pytz
    
    entered_at = request.session['entered_at']
    entered_at = datetime.strptime(entered_at, "%m-%d-%Y")
    day_start = entered_at.replace(hour=00, minute=00)
    day_end = entered_at.replace(hour=23, minute=59)
    
    timezone = pytz.timezone("America/Los_Angeles")
    day_start = timezone.localize(day_start)
    day_end = timezone.localize(day_end)
    
    entries = Entry.objects.filter(customer=customer, 
                                   entered_at__lt=day_end, 
                                   entered_at__gte=day_start)