Created
October 8, 2022 22:40
-
-
Save rileypeterson/aaa827ae4cd6c691a0215c2f0b4dccd2 to your computer and use it in GitHub Desktop.
Convert timezone in django annotate with date and time fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Insane Django operation I had to do | |
# Inspired by: https://stackoverflow.com/a/70552577/8927098 | |
# Need to filter for a date, but source table date is in UTC and it's separated into date and time fields | |
# Example: | |
# Date to find (America/New_York): 2005-09-08 | |
# Date in table (UTC): 2005-09-09 | |
# Time in table (UTC): 01:07:00 | |
# So converting what's in the table from UTC to America/New_York gives | |
# Date in table (America/New_York): 2005-09-08 | |
# Time in table (America/New_York): 21:07:00 | |
# Here's a way (probably not the best way) to do this: | |
from django.db.models import Func, ExpressionWrapper, F, DateTimeField, DateField | |
class AtTimeZone(Func): | |
function = "AT TIME ZONE" | |
template = "(%(expressions)s %(function)s 'UTC') %(function)s 'America/New_York'" | |
YourModel.objects.annotate( | |
# Add date and time fields | |
datetime=ExpressionWrapper( | |
F("date") + F("time"), output_field=DateTimeField() | |
), | |
# Run AtTimeZone Func on datetime field | |
datetime_et=AtTimeZone(F("datetime")), | |
).filter( | |
# Use __date here to get back to date field | |
datetime_et__date=datetime(2005, 9, 8) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to change this to passing dynamically user timezone stored in db
for example
AtTimezone(F('datetime'),F('user_timezone')
)