You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

datetime.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. from datetime import datetime
  2. from django.conf import settings
  3. from django.db.models.expressions import Func
  4. from django.db.models.fields import (
  5. DateField, DateTimeField, DurationField, Field, IntegerField, TimeField,
  6. )
  7. from django.db.models.lookups import (
  8. Transform, YearExact, YearGt, YearGte, YearLt, YearLte,
  9. )
  10. from django.utils import timezone
  11. class TimezoneMixin:
  12. tzinfo = None
  13. def get_tzname(self):
  14. # Timezone conversions must happen to the input datetime *before*
  15. # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
  16. # database as 2016-01-01 01:00:00 +00:00. Any results should be
  17. # based on the input datetime not the stored datetime.
  18. tzname = None
  19. if settings.USE_TZ:
  20. if self.tzinfo is None:
  21. tzname = timezone.get_current_timezone_name()
  22. else:
  23. tzname = timezone._get_timezone_name(self.tzinfo)
  24. return tzname
  25. class Extract(TimezoneMixin, Transform):
  26. lookup_name = None
  27. output_field = IntegerField()
  28. def __init__(self, expression, lookup_name=None, tzinfo=None, **extra):
  29. if self.lookup_name is None:
  30. self.lookup_name = lookup_name
  31. if self.lookup_name is None:
  32. raise ValueError('lookup_name must be provided')
  33. self.tzinfo = tzinfo
  34. super().__init__(expression, **extra)
  35. def as_sql(self, compiler, connection):
  36. sql, params = compiler.compile(self.lhs)
  37. lhs_output_field = self.lhs.output_field
  38. if isinstance(lhs_output_field, DateTimeField):
  39. tzname = self.get_tzname()
  40. sql = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
  41. elif isinstance(lhs_output_field, DateField):
  42. sql = connection.ops.date_extract_sql(self.lookup_name, sql)
  43. elif isinstance(lhs_output_field, TimeField):
  44. sql = connection.ops.time_extract_sql(self.lookup_name, sql)
  45. elif isinstance(lhs_output_field, DurationField):
  46. if not connection.features.has_native_duration_field:
  47. raise ValueError('Extract requires native DurationField database support.')
  48. sql = connection.ops.time_extract_sql(self.lookup_name, sql)
  49. else:
  50. # resolve_expression has already validated the output_field so this
  51. # assert should never be hit.
  52. assert False, "Tried to Extract from an invalid type."
  53. return sql, params
  54. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  55. copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
  56. field = copy.lhs.output_field
  57. if not isinstance(field, (DateField, DateTimeField, TimeField, DurationField)):
  58. raise ValueError(
  59. 'Extract input expression must be DateField, DateTimeField, '
  60. 'TimeField, or DurationField.'
  61. )
  62. # Passing dates to functions expecting datetimes is most likely a mistake.
  63. if type(field) == DateField and copy.lookup_name in ('hour', 'minute', 'second'):
  64. raise ValueError(
  65. "Cannot extract time component '%s' from DateField '%s'. " % (copy.lookup_name, field.name)
  66. )
  67. return copy
  68. class ExtractYear(Extract):
  69. lookup_name = 'year'
  70. class ExtractIsoYear(Extract):
  71. """Return the ISO-8601 week-numbering year."""
  72. lookup_name = 'iso_year'
  73. class ExtractMonth(Extract):
  74. lookup_name = 'month'
  75. class ExtractDay(Extract):
  76. lookup_name = 'day'
  77. class ExtractWeek(Extract):
  78. """
  79. Return 1-52 or 53, based on ISO-8601, i.e., Monday is the first of the
  80. week.
  81. """
  82. lookup_name = 'week'
  83. class ExtractWeekDay(Extract):
  84. """
  85. Return Sunday=1 through Saturday=7.
  86. To replicate this in Python: (mydatetime.isoweekday() % 7) + 1
  87. """
  88. lookup_name = 'week_day'
  89. class ExtractQuarter(Extract):
  90. lookup_name = 'quarter'
  91. class ExtractHour(Extract):
  92. lookup_name = 'hour'
  93. class ExtractMinute(Extract):
  94. lookup_name = 'minute'
  95. class ExtractSecond(Extract):
  96. lookup_name = 'second'
  97. DateField.register_lookup(ExtractYear)
  98. DateField.register_lookup(ExtractMonth)
  99. DateField.register_lookup(ExtractDay)
  100. DateField.register_lookup(ExtractWeekDay)
  101. DateField.register_lookup(ExtractWeek)
  102. DateField.register_lookup(ExtractIsoYear)
  103. DateField.register_lookup(ExtractQuarter)
  104. TimeField.register_lookup(ExtractHour)
  105. TimeField.register_lookup(ExtractMinute)
  106. TimeField.register_lookup(ExtractSecond)
  107. DateTimeField.register_lookup(ExtractHour)
  108. DateTimeField.register_lookup(ExtractMinute)
  109. DateTimeField.register_lookup(ExtractSecond)
  110. ExtractYear.register_lookup(YearExact)
  111. ExtractYear.register_lookup(YearGt)
  112. ExtractYear.register_lookup(YearGte)
  113. ExtractYear.register_lookup(YearLt)
  114. ExtractYear.register_lookup(YearLte)
  115. ExtractIsoYear.register_lookup(YearExact)
  116. ExtractIsoYear.register_lookup(YearGt)
  117. ExtractIsoYear.register_lookup(YearGte)
  118. ExtractIsoYear.register_lookup(YearLt)
  119. ExtractIsoYear.register_lookup(YearLte)
  120. class Now(Func):
  121. template = 'CURRENT_TIMESTAMP'
  122. output_field = DateTimeField()
  123. def as_postgresql(self, compiler, connection, **extra_context):
  124. # PostgreSQL's CURRENT_TIMESTAMP means "the time at the start of the
  125. # transaction". Use STATEMENT_TIMESTAMP to be cross-compatible with
  126. # other databases.
  127. return self.as_sql(compiler, connection, template='STATEMENT_TIMESTAMP()', **extra_context)
  128. class TruncBase(TimezoneMixin, Transform):
  129. kind = None
  130. tzinfo = None
  131. def __init__(self, expression, output_field=None, tzinfo=None, **extra):
  132. self.tzinfo = tzinfo
  133. super().__init__(expression, output_field=output_field, **extra)
  134. def as_sql(self, compiler, connection):
  135. inner_sql, inner_params = compiler.compile(self.lhs)
  136. if isinstance(self.output_field, DateTimeField):
  137. tzname = self.get_tzname()
  138. sql = connection.ops.datetime_trunc_sql(self.kind, inner_sql, tzname)
  139. elif isinstance(self.output_field, DateField):
  140. sql = connection.ops.date_trunc_sql(self.kind, inner_sql)
  141. elif isinstance(self.output_field, TimeField):
  142. sql = connection.ops.time_trunc_sql(self.kind, inner_sql)
  143. else:
  144. raise ValueError('Trunc only valid on DateField, TimeField, or DateTimeField.')
  145. return sql, inner_params
  146. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  147. copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
  148. field = copy.lhs.output_field
  149. # DateTimeField is a subclass of DateField so this works for both.
  150. assert isinstance(field, (DateField, TimeField)), (
  151. "%r isn't a DateField, TimeField, or DateTimeField." % field.name
  152. )
  153. # If self.output_field was None, then accessing the field will trigger
  154. # the resolver to assign it to self.lhs.output_field.
  155. if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)):
  156. raise ValueError('output_field must be either DateField, TimeField, or DateTimeField')
  157. # Passing dates or times to functions expecting datetimes is most
  158. # likely a mistake.
  159. class_output_field = self.__class__.output_field if isinstance(self.__class__.output_field, Field) else None
  160. output_field = class_output_field or copy.output_field
  161. has_explicit_output_field = class_output_field or field.__class__ is not copy.output_field.__class__
  162. if type(field) == DateField and (
  163. isinstance(output_field, DateTimeField) or copy.kind in ('hour', 'minute', 'second', 'time')):
  164. raise ValueError("Cannot truncate DateField '%s' to %s. " % (
  165. field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
  166. ))
  167. elif isinstance(field, TimeField) and (
  168. isinstance(output_field, DateTimeField) or
  169. copy.kind in ('year', 'quarter', 'month', 'week', 'day', 'date')):
  170. raise ValueError("Cannot truncate TimeField '%s' to %s. " % (
  171. field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
  172. ))
  173. return copy
  174. def convert_value(self, value, expression, connection):
  175. if isinstance(self.output_field, DateTimeField):
  176. if not settings.USE_TZ:
  177. pass
  178. elif value is not None:
  179. value = value.replace(tzinfo=None)
  180. value = timezone.make_aware(value, self.tzinfo)
  181. elif not connection.features.has_zoneinfo_database:
  182. raise ValueError(
  183. 'Database returned an invalid datetime value. Are time '
  184. 'zone definitions for your database installed?'
  185. )
  186. elif isinstance(value, datetime):
  187. if value is None:
  188. pass
  189. elif isinstance(self.output_field, DateField):
  190. value = value.date()
  191. elif isinstance(self.output_field, TimeField):
  192. value = value.time()
  193. return value
  194. class Trunc(TruncBase):
  195. def __init__(self, expression, kind, output_field=None, tzinfo=None, **extra):
  196. self.kind = kind
  197. super().__init__(expression, output_field=output_field, tzinfo=tzinfo, **extra)
  198. class TruncYear(TruncBase):
  199. kind = 'year'
  200. class TruncQuarter(TruncBase):
  201. kind = 'quarter'
  202. class TruncMonth(TruncBase):
  203. kind = 'month'
  204. class TruncWeek(TruncBase):
  205. """Truncate to midnight on the Monday of the week."""
  206. kind = 'week'
  207. class TruncDay(TruncBase):
  208. kind = 'day'
  209. class TruncDate(TruncBase):
  210. kind = 'date'
  211. lookup_name = 'date'
  212. output_field = DateField()
  213. def as_sql(self, compiler, connection):
  214. # Cast to date rather than truncate to date.
  215. lhs, lhs_params = compiler.compile(self.lhs)
  216. tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
  217. sql = connection.ops.datetime_cast_date_sql(lhs, tzname)
  218. return sql, lhs_params
  219. class TruncTime(TruncBase):
  220. kind = 'time'
  221. lookup_name = 'time'
  222. output_field = TimeField()
  223. def as_sql(self, compiler, connection):
  224. # Cast to time rather than truncate to time.
  225. lhs, lhs_params = compiler.compile(self.lhs)
  226. tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
  227. sql = connection.ops.datetime_cast_time_sql(lhs, tzname)
  228. return sql, lhs_params
  229. class TruncHour(TruncBase):
  230. kind = 'hour'
  231. class TruncMinute(TruncBase):
  232. kind = 'minute'
  233. class TruncSecond(TruncBase):
  234. kind = 'second'
  235. DateTimeField.register_lookup(TruncDate)
  236. DateTimeField.register_lookup(TruncTime)