From 477129de46032635fb6ccbdce51b3be1431125f7 Mon Sep 17 00:00:00 2001 From: XingQue Date: Wed, 15 Jul 2026 23:53:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(merchant):=20=E6=93=8D=E4=BD=9C=E4=BA=BA?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E6=97=B6=E9=97=B4=E7=AD=9B=E9=80=89=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=20USE=5FTZ=3DFalse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MySQL 在关闭 USE_TZ 时不接受 timezone-aware datetime,解析为 naive 再查询。 Co-authored-by: Cursor --- merchant_ops/services/action_stats.py | 39 ++++++++++++++++++--------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/merchant_ops/services/action_stats.py b/merchant_ops/services/action_stats.py index 2db3ced..bdcdd16 100644 --- a/merchant_ops/services/action_stats.py +++ b/merchant_ops/services/action_stats.py @@ -15,22 +15,35 @@ from products.models import ShangpinLeixing def _parse_dt(value, end_of_day=False): + """解析时间;USE_TZ=False 时必须返回 naive datetime(MySQL)。""" if value is None or value == '': return None + dt = None if isinstance(value, datetime): - return value - text = str(value).strip().replace('/', '-') - for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d'): - try: - dt = datetime.strptime(text, fmt) - if fmt == '%Y-%m-%d' and end_of_day: - dt = dt.replace(hour=23, minute=59, second=59) - if timezone.is_naive(dt): - dt = timezone.make_aware(dt, timezone.get_current_timezone()) - return dt - except ValueError: - continue - return None + dt = value + else: + text = str(value).strip().replace('/', '-') + for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d'): + try: + dt = datetime.strptime(text, fmt) + if fmt == '%Y-%m-%d' and end_of_day: + dt = dt.replace(hour=23, minute=59, second=59) + break + except ValueError: + continue + if dt is None: + return None + + from django.conf import settings + use_tz = bool(getattr(settings, 'USE_TZ', False)) + + if use_tz: + if timezone.is_naive(dt): + dt = timezone.make_aware(dt, timezone.get_current_timezone()) + else: + if timezone.is_aware(dt): + dt = timezone.make_naive(dt, timezone.get_current_timezone()) + return dt def _money(val):