Login

Querying datetime aware objects in your local timezone

Author:
jayliew
Posted:
May 27, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

I have a model with a datetime field that I used as a timestamp. I’m in California’s timezone (“America/Los_Angeles”). The data is saved in UTC in MySQL (as confirmed by the ORM). I just want to do a query that looks like this: “give me all the information with day X’s timestamp” (24 hour period). But the timestamp is a datetime, not date. If you just do varname.date(), it’s still UTC’s date, not your local timezone’s date. Here’s what I did:

  1. First construct the start and end time period covering the 24 hour period of that day you want

  2. Make it an “aware” (not naive) datetime

  3. Filter for the __range

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django.utils.dateparse import parse_datetime
import pytz
s1 = '2012-05-03 00:00:00' # start time
s2 = '2012-05-03 23:59:59' # end time, together covers 1 day
la = pytz.timezone('America/Los_Angeles')
n1 = parse_datetime(s1) # naive object
n2 = parse_datetime(s2)
aware_start_time = la.localize(n2) # aware object
aware_end_time = la.localize(n1)
MyModel.objects.filter(timestamp__range=(aware_start_time, aware_end_time))) # 'timestamp' is a datetime field

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.