Login

Querying datetime aware objects in your local timezone

Author:
jayliew
Posted:
May 27, 2012
Language:
Python
Version:
Not specified
Tags:
datetime timezone queryset utc local datetimefield
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. UTC-based astimezone filter by miracle2k 3 years, 6 months ago
  2. UTC DateTime field by ludo 7 years, 8 months ago
  3. astimezone template tag by whardier 4 years, 1 month ago
  4. JSON encode ISO UTC datetime by japerk 6 years ago
  5. Converting PDT to UTC using pytz and dateutil by simon 6 years, 8 months ago

Comments

Please login first before commenting.