Skip to content

Commit e21418e

Browse files
committed
INTPYTHON-968 Fix Extract database function with fixed offset tzinfo
1 parent 09e30a0 commit e21418e

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

django_mongodb_backend/functions.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,15 @@ def cot(self, compiler, connection):
100100
return {"$divide": [1, {"$tan": lhs_mql}]}
101101

102102

103+
def _get_extract_timezone(self):
104+
tzname = self.get_tzname()
105+
# Django formats fixed offset zones as "UTC+HH:MM" but MongoDB only accepts
106+
# the bare offset form "+HH:MM" / "-HH:MM".
107+
if tzname and tzname.startswith(("UTC+", "UTC-")):
108+
return tzname[3:]
109+
return tzname
110+
111+
103112
def extract(self, compiler, connection):
104113
lhs_mql = process_lhs(self, compiler, connection, as_expr=True)
105114
# ExtractQuarter lacks a built-in operator.
@@ -108,14 +117,14 @@ def extract(self, compiler, connection):
108117
operator = EXTRACT_OPERATORS.get(self.lookup_name)
109118
if operator is None:
110119
raise NotSupportedError(f"{self.__class__.__name__} is not supported.")
111-
if timezone := self.get_tzname():
120+
if timezone := _get_extract_timezone(self):
112121
lhs_mql = {"date": lhs_mql, "timezone": timezone}
113122
return {f"${operator}": lhs_mql}
114123

115124

116125
def extract_quarter(self, compiler, connection):
117126
lhs_mql = process_lhs(self, compiler, connection, as_expr=True)
118-
if timezone := self.get_tzname():
127+
if timezone := _get_extract_timezone(self):
119128
lhs_mql = {"date": lhs_mql, "timezone": timezone}
120129
return {"$ceil": {"$divide": [{"$month": lhs_mql}, 3]}}
121130

docs/releases/6.0.x.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ New features
1717
- :class:`~django.db.models.functions.Right`
1818
- :class:`~django.db.models.functions.SHA256` (requires MongoDB 8.3+)
1919

20+
- Added support for fixed-offset ``tzinfo`` in the
21+
:class:`~django.db.models.functions.Extract` database functions.
22+
2023
- Added support for Django's warning when performing import-time queries.
2124

2225
Bug fixes

0 commit comments

Comments
 (0)