- 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:
-
First construct the start and end time period covering the 24 hour period of that day you want
-
Make it an “aware” (not naive) datetime
-
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.